Sometimes, we want to make a Python asyncio call from a Flask route.
In this article, we’ll look at how to make a Python asyncio call from a Flask route.
How to make a Python asyncio call from a Flask route?
To make a Python asyncio call from a Flask route, we can call run_until_complete
.
For instance, we write
import asyncio
from flask import Flask
async def foo(a):
print(a)
loop = asyncio.get_event_loop()
app = Flask(__name__)
@app.route("/")
def notify():
loop.run_until_complete(foo("abc"))
return "OK"
if __name__ == "__main__":
app.run(debug=False, use_reloader=False)
to create the event loop with get_event_loop
.
Then we call loop.run_until_complete
with the async function to run in the notify
view.
Conclusion
To make a Python asyncio call from a Flask route, we can call run_until_complete
.