Using a tornado with aiohttp (or other asynchronous libraries)

I want to use a tornado with asynchronous libraries like aiohttp and native python 3.5 coroutines, and it seems to be supported in the latest tornado release (4.3). However, when it is used in a tornado event loop, the request handler hangs indefinitely. If you do not use aiohttp (i.e., without the lines r = await aiohttp.get('http://google.com/') and text = await r.text() below), the request handler is executed as usual.

My test code is as follows:

 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() 
+5
source share
1 answer

According to docs , you are doing it almost right. You must create / init Tornado ioloop with the corresponding asyncio, since aiohttp runs on 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().start() 

The reason your code gets stuck is because asyncio ioloop actually doesn't work, only Tornado, so await waits indefinitely.

+10
source

Source: https://habr.com/ru/post/1240498/


All Articles