首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在tornado.wsgi.WSGIContainer中使用异步龙卷风API?

如何在tornado.wsgi.WSGIContainer中使用异步龙卷风API?
EN

Stack Overflow用户
提问于 2014-01-30 14:48:56
回答 1查看 1.6K关注 0票数 2

我尝试使用应该与异步操作一起工作的自定义WSGIContainer:

代码语言:javascript
复制
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函数的结果。另外,下面的代码不起作用:

代码语言:javascript
复制
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接口,并允许编写自定义适配器,使之成为异步的。

EN

回答 1

Stack Overflow用户

发布于 2014-01-30 15:23:57

WSGI不适用于异步。

通常,要使函数等待龙卷风协同器完成,函数本身必须是协同线,并且必须yield协同器的结果:

代码语言:javascript
复制
@gen.coroutine
def caller():
    res = yield try_to_download()

但是,当然,像simple_app这样的WSGI函数不可能是协同作用,因为WSGI不理解协同。关于WSGI和异步之间不兼容性的更彻底的解释是在瓶装文件中。

如果您必须支持WSGI,不要使用旋风式的AsyncHTTPClient,而是使用像标准的urllib2或PyCurl这样的同步客户端。如果你必须使用龙卷风的AsyncHTTPClient,不要使用WSGI。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21459642

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档