简体   繁体   English

使用python的BaseHTTPRequestHandler在HTTP请求之间保持状态

[英]Keeping state between HTTP requests with python's BaseHTTPRequestHandler

I have a HTTP handler derived from BaseHTTPRequestHandler 我有一个从BaseHTTPRequestHandler派生的HTTP处理程序

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. 似乎对于每个请求都调用了一个新的处理程序实例,因此我无法将我的程序状态保存在MyHandler中。 I could store state globally but for design reasons I don't want to do that. 我可以在全球范围内存储州,但出于设计原因,我不想这样做。 Are there any other options? 还有其他选择吗?

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: 然后在你的处理程序的do_GET中你可以做类似的事情:

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

Which should then be referable by other instance of do_GET. 然后应该由do_GET的其他实例引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM