Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping state between HTTP requests with python's BaseHTTPRequestHandler

Tags:

python

http

I have a HTTP handler derived from BaseHTTPRequestHandler

class MyHandler(BaseHTTPRequestHandler):
    do_GET():
        ...

The problem I've been having is that I'd like to report the state of my application running in another thread. It seems that for every request a new instance of handler is called so I can't keep my program state in MyHandler. I could store state globally but for design reasons I don't want to do that. Are there any other options?

like image 939
user1816847 Avatar asked Nov 03 '22 18:11

user1816847


1 Answers

You can use the multiprocessing module to accomplish this. First derive a server class:

class MyTCPServer(SocketServer.ForkingTCPServer):
    manager = multiprocessing.Manager()
    SHARED = manager.dict()

Then in your handler's do_GET you can do something like:

self.server.SHARED['foo'] = 1

Which should then be referable by other instance of do_GET.

like image 77
MattK Avatar answered Nov 08 '22 06:11

MattK