Synex

2 min read495 words 9

Running Asynchronous Python Code

🧠 Running Asynchronous Python Code with Flask using ASGI

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.


πŸš€ Table of Contents

  1. Why Flask Alone Isn’t Async
  2. What is ASGI?
  3. Option 1: Use Quart for True Async Support
  4. Option 2: Wrap Flask in ASGI (Limited)
  5. Summary Table
  6. Final Thoughts

❓ Why Flask Alone Isn’t Async

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.
  • Blocking code like time.sleep() or requests.get() can halt the entire server.

⚑ What is ASGI?

ASGI stands for Asynchronous Server Gateway Interface. It's the modern, async-compatible replacement for WSGI.

With ASGI, you can:

  • Write non-blocking async def endpoints.
  • Handle many requests concurrently.
  • Use async libraries like httpx, asyncpg, or aiomysql.

βœ… Option 1: Use Quart for True Async Support

Quart is an ASGI-compatible web framework with an API that's nearly identical to Flask.

πŸ”§ Installation

bash pip install quart uvicorn

πŸ§ͺ Example

python

app.py

from quart import Quart import asyncio

app = Quart(name)

@app.route("/async") async def async_route(): await asyncio.sleep(2) return "This was async!"

πŸš€ Run with ASGI server

bash uvicorn app:app

βœ… Now you're running async code properly, with full event loop concurrency.


⚠️ Option 2: Wrap Flask in ASGI (Limited)

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.

πŸ”§ Installation

bash pip install flask uvicorn asgiref

πŸ§ͺ Example

python

app.py

from flask import Flask from asgiref.wsgi import WsgiToAsgi

app = Flask(name)

@app.route("/") def hello(): return "Hello from Flask!"

asgi_app = WsgiToAsgi(app)

πŸš€ Run with Uvicorn

bash uvicorn app:asgi_app

⚠️ async def views won't work asynchronously β€” Flask is still synchronous under the hood.


πŸ“Š Summary Table

Feature Flask (WSGI) Flask + ASGI Adapter Quart (ASGI)
Supports async def routes ❌ ❌ βœ…
Runs under ASGI server ❌ βœ… βœ…
True async concurrency ❌ ❌ βœ…
Compatible with Flask APIs βœ… βœ… βœ…

🧩 Final Thoughts

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 like Celery with aiohttp.



Read the next story first in the Cizeex app.

CIZEEX
PREPARING