我尝试使用应该与异步操作一起工作的自定义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。
你可能会问我为什么不想使用本机tornado.web.RequestHandler.主要原因是我有自定义python (WsgiDAV),它生成WSGI接口,并允许编写自定义适配器,使之成为异步的。
发布于 2014-01-30 15:23:57
WSGI不适用于异步。
通常,要使函数等待龙卷风协同器完成,函数本身必须是协同线,并且必须yield协同器的结果:
@gen.coroutine
def caller():
res = yield try_to_download()但是,当然,像simple_app这样的WSGI函数不可能是协同作用,因为WSGI不理解协同。关于WSGI和异步之间不兼容性的更彻底的解释是在瓶装文件中。
如果您必须支持WSGI,不要使用旋风式的AsyncHTTPClient,而是使用像标准的urllib2或PyCurl这样的同步客户端。如果你必须使用龙卷风的AsyncHTTPClient,不要使用WSGI。
https://stackoverflow.com/questions/21459642
复制相似问题