[Flask] asyncio Methods in Flask
asyncio Methods in Flask
Flask is a synchronous framework based on WSGI, which doesn't natively support asynchronous programming with
async/await. However, it’s still possible to run asynchronous code within Flask by using Python's built-in asyncio event loop.How it Works
When an async function needs to run inside a Flask route, an event loop can explicitly execute it
from flask import Flask, request, render_templateimport asyncio
app = Flask(__name__)
@app.route('/search', methods=['POST'])def search(): keyword = request.form['keyword']
loop = asyncio.new_event_loop() asyncio.set_event_loop(loop)
# Run the async function synchronously result = loop.run_until_complete(resolve_game_entry(keyword))
loop.close()
return render_template('result.html', result=result)
The Limitation (Important):
Although this approach lets asynchronous code run inside Flask, there's a significant downside:
-
The Flask application waits (blocks) while
run_until_complete()executes. -
No other routes or tasks within the same Flask instance can run concurrently during this time.
-
In other words, the asynchronous function is effectively converted into synchronous, eliminating the performance benefit of true concurrency.
Comments
Post a Comment