by orf · 9y ago · 0 comments
from asyncio import wait, gather, get_event_loop
from aiohttp import web
async my_handler(request):
handle1 = call_webservice_1(args)
handle2 = call_webservice_2(args)
handle3 = call_webservice_3(args)
await wait(gather(handle1, handle2, handle3), 500)
return web.Response({'finished': True})
app = web.Application()
app.router.add_route('GET', '/test/', my_handler)
loop = asyncio.get_event_loop()
server = loop.create_server(app.make_handler())
loop.run_until_complete(server)
Done. Not flask, but if you need to make lots of parallel network calls during a web request why the hell are you using flask?If the answer is "to get some async goodness, just use this easy code, plus rewrite your entire project to use a different framework and set of libraries", then we are only fooling ourselves.
I would recommend against it, but if you had an existing framework, you could just make the endpoints lambdas that are something like:
app.route("/whatever", lambda: loop.run_until_complete(async_handler_function())) res = await get('https://somesite.com')
return Response(res['data'])
As you'd get the same thing if you just did it synchronously (without the await). But if you want to fetch 2 or more pages in parallel when it really pays off.Flask with gunicorn has its own even loop and asyncio io another one and at the end it is hard to be sure if something is working because I am lucky or because it is the way to do things.
Anyway, thank you for your example, it is really clear and easy to understand! Maybe we need a flask like framework which is asyncio based. Which mean I will need to upgrade the code to Python 3 :)