Web frameworks like Flask are traditionally synchronous, which can be limiting if you want to take advantage of Python's asyncio capabilities. In this guide, you'll learn how to run asynchronous code using Flask, and why switching to ASGI (Asynchronous Server Gateway Interface) or using Quart might be your best path forward.
By default, Flask runs on WSGI (Web Server Gateway Interface), a standard that doesn't support asynchronous code execution.
async def routes will still run synchronously.time.sleep() or requests.get() can halt the entire server.ASGI stands for Asynchronous Server Gateway Interface. It's the modern, async-compatible replacement for WSGI.
With ASGI, you can:
async def endpoints.httpx, asyncpg, or aiomysql.Quart is an ASGI-compatible web framework with an API that's nearly identical to Flask.
bash pip install quart uvicorn
python
from quart import Quart import asyncio
app = Quart(name)
@app.route("/async") async def async_route(): await asyncio.sleep(2) return "This was async!"
bash uvicorn app:app
β Now you're running async code properly, with full event loop concurrency.
If you want to stick with Flask, you can serve it via ASGI using an adapter. This wonβt give you true async views but allows integration into an ASGI stack.
bash pip install flask uvicorn asgiref
python
from flask import Flask from asgiref.wsgi import WsgiToAsgi
app = Flask(name)
@app.route("/") def hello(): return "Hello from Flask!"
asgi_app = WsgiToAsgi(app)
bash uvicorn app:asgi_app
β οΈ
async defviews won't work asynchronously β Flask is still synchronous under the hood.
| Feature | Flask (WSGI) | Flask + ASGI Adapter | Quart (ASGI) |
|---|---|---|---|
Supports async def routes |
β | β | β |
| Runs under ASGI server | β | β | β |
| True async concurrency | β | β | β |
| Compatible with Flask APIs | β | β | β |
If you're building high-performance APIs or handling long-running I/O tasks, using Quart + Uvicorn is the most reliable way to run async Python code effectively.
βοΈ Want to keep your Flask app but run background async jobs? You can also explore
asyncio.create_task(),aiojobs, or use task queues likeCelerywithaiohttp.
Join Synex to get notified about similar articles, discover new content, and share your own knowledge with the world!