如何在Python中使用多进程运行simple_server中的make_server?
我有一个简单的wsgi程序。
from wsgiref.simple_server import make_server
import time
def application(environ, start_response):
response_body = 'Hello World'
status = '200 OK'
response_headers = [('Content-Type', 'text/plain'),
('Content-Length', str(len(response_body)))]
start_response(status, response_headers)
if environ['PATH_INFO'] != '/favicon.ico':
print "Time :", int(time.time())
if int(time.time()) % 2:
print "Even"
time.sleep(10)
else:
print "Odd"
return [response_body]
httpd = make_server('localhost', 8000, application)
httpd.serve_forever()
根据代码,如果timestamp
是偶数
,那么它会在10秒后发送响应。但如果timestamp
是奇数
,那么它会直接发送响应,不会等待。
我的问题是,如果我发送两个请求,假如第一个请求是偶数
模式,那么第二个请求会在第一个请求完成后才能处理。
我查了一下解决方案,发现使用multiprocess
可以解决这个问题。我在apache的配置中设置了multiprocess
。这样我就能在没有完成偶数
请求的情况下,直接得到奇数
请求的响应。
我还查了如何在simple_server
模块的make_server
方法中设置multiprocess
。当我运行python /usr/lib64/python2.7/wsgiref/simple_server.py
时,输出的最后几行是:
wsgi.errors = <open file '<stderr>', mode 'w' at 0x7f22ba2a1270>
wsgi.file_wrapper = <class wsgiref.util.FileWrapper at 0x1647600>
wsgi.input = <socket._fileobject object at 0x1569cd0>
wsgi.multiprocess = False
wsgi.multithread = True
wsgi.run_once = False
wsgi.url_scheme = 'http'
wsgi.version = (1, 0)
所以我在寻找如何设置这个make_server
的multiprocess
,这样make_server
就能处理多个请求,即使有请求正在进行中。
谢谢大家!
1 个回答
2
如果你在使用Apache和mod_wsgi,那你就不需要担心make_server/serve_forever
这些东西了。因为Apache本身就是一个网络服务器,它会为你处理这些事情。它会管理进程,并运行application
这个回调函数。
确保你的Apache和mod_wsgi配置允许多进程和多线程。你可以在这里找到很好的参考资料。