Performance: Migrating to async Flask
This affects server response time and how efficiently the server handles multiple requests concurrently, impacting user wait time and server throughput.
from flask import Flask import asyncio app = Flask(__name__) @app.route('/') async def index(): await asyncio.sleep(2) # non-blocking return 'Hello, World!' if __name__ == '__main__': app.run(debug=True, use_reloader=False)
from flask import Flask app = Flask(__name__) @app.route('/') def index(): import time time.sleep(2) # blocking operation return 'Hello, World!' if __name__ == '__main__': app.run()
| Pattern | Server Blocking | Concurrent Requests | Response Latency | Verdict |
|---|---|---|---|---|
| Synchronous Flask route with blocking calls | Blocks server thread | Handles 1 request at a time | High latency under load | [X] Bad |
| Async Flask route with await for I/O | Non-blocking | Handles many requests concurrently | Lower latency under load | [OK] Good |
async def functions?async def and can use await inside.from flask import Flask
import asyncio
app = Flask(__name__)
@app.route('/')
async def home():
await asyncio.sleep(0.1)
return 'Done'await asyncio.sleep(0.1) which pauses the function asynchronously for 0.1 seconds.from flask import Flask
app = Flask(__name__)
@app.route('/')
async def index():
return 'Hello'async def fetch_data(). Which is the correct way to write the route?fetch_data(), you must use await inside an async function.Pass the test and this pattern moves unknown