我尝试使用应该与异步操作一起使用的自定义 WSGIContainer:
from tornado import httpserver, httpclient, ioloop, wsgi, gen
@gen.coroutine
def try_to_download():
response = yield httpclient.AsyncHTTPClient().fetch("http://www.stackoverflow.com/")
raise gen.Return(response.body)
def simple_app(environ, start_response):
res = try_to_download()
print 'done: ', res.done()
print 'exec_info: ', res.exc_info()
status = "200 OK"
response_headers = [("Content-type", "text/html")]
start_response(status, response_headers)
return ['hello world']
container = wsgi.WSGIContainer(simple_app)
http_server = httpserver.HTTPServer(container)
http_server.listen(8888)
ioloop.IOLoop.instance().start()
但这行不通。似乎应用程序不等待try_to_download函数结果。下面的代码也不起作用:
from tornado import httpserver, httpclient, ioloop, wsgi, gen
@gen.coroutine
def try_to_download():
yield gen.Task(httpclient.AsyncHTTPClient().fetch, "http://www.stackoverflow.com/")
def simple_app(environ, start_response):
res = try_to_download()
print 'done: ', res.done()
print 'exec_info: ', res.exc_info()
status = "200 OK"
response_headers = [("Content-type", "text/html")]
start_response(status, response_headers)
return ['hello world']
container = wsgi.WSGIContainer(simple_app)
http_server = httpserver.HTTPServer(container)
http_server.listen(8888)
ioloop.IOLoop.instance().start()
你有什么想法为什么它不起作用?我使用的 Python 版本是 2.7。
PS 你可能会问我为什么不想使用原生tornado.web.RequestHandler。主要原因是我有自定义 python 库(WsgiDAV),它产生 WSGI 接口并允许编写自定义适配器,我可以使它们异步。