使用龙卷风和aiohttp(或其他基于asyncio的库)

Leo*_*nth 9 tornado python-3.x python-asyncio aiohttp

我想使用龙卷风和asyncio库,如aiohttp和本机python 3.5协同程序,它似乎在最新的龙卷风版本(4.3)中得到支持.但是,在龙卷风事件循环中使用它时,请求处理程序将无限期挂起.当不使用aiohttp(即没有行r = await aiohttp.get('http://google.com/')text = await r.text()下面)时,请求处理程序正常进行.

我的测试代码如下:

from tornado.ioloop import IOLoop
import tornado.web
import tornado.httpserver
import aiohttp

IOLoop.configure('tornado.platform.asyncio.AsyncIOLoop')


class MainHandler(tornado.web.RequestHandler):
    async def get(self):
        r = await aiohttp.get('http://google.com/')
        text = await r.text()
        self.write("Hello, world, text is: {}".format(text))

if __name__ == "__main__":
    app = tornado.web.Application([
        (r"/", MainHandler),
    ])
    server = tornado.httpserver.HTTPServer(app)
    server.bind(8888, '127.0.0.1')
    server.start()
    IOLoop.current().start()
Run Code Online (Sandbox Code Playgroud)

kwa*_*nek 12

根据文档,你几乎是正确的.你必须用相应的asyncio创建/ init Tornado的ioloop,因为aiohttp在asyncio上运行.

from tornado.ioloop import IOLoop
import tornado.web
import tornado.httpserver
import aiohttp
from tornado.platform.asyncio import AsyncIOMainLoop
import asyncio

class MainHandler(tornado.web.RequestHandler):
    async def get(self):
        r = await aiohttp.get('http://google.com/')
        text = await r.text()
        self.write("Hello, world, text is: {}".format(text))

if __name__ == "__main__":
    AsyncIOMainLoop().install()
    app = tornado.web.Application([
        (r"/", MainHandler),
    ])
    server = tornado.httpserver.HTTPServer(app)
    server.bind(1234, '127.0.0.1')
    server.start()
    asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud)

您的代码卡住的原因是asyncio的ioloop实际上没有运行,只有Tornado的运行,所以await无限期地等待.