Last Updated : 01 Apr, 2025
Flask is inherently synchronous, meaning each request is processed one at a time. However, modern web applications often require handling multiple tasks simultaneously, such as:
Asynchronous programming allows us to execute multiple tasks concurrently, improving performance and responsiveness.
With Python's built-in asyncio, we can introduce asynchronous behavior in Flask applications, allowing tasks like database queries and API requests to run without blocking the main application thread.
Features of asynchronous programmingBefore using async.io in Flask, let’s understand how asynchronous functions work in Python.
Declaring an Asynchronous FunctionIn Python, asynchronous functions are defined using the async def keyword:
Python
import asyncio
async def my_async_function():
print("Task started")
await asyncio.sleep(2) # Simulates an async operation
print("Task completed")
# Running the async function
asyncio.run(my_async_function())
Explanation:
To run multiple async functions concurrently, use asyncio.gather():
Python
async def task_1():
await asyncio.sleep(2)
return "Task 1 Complete"
async def task_2():
await asyncio.sleep(3)
return "Task 2 Complete"
async def main():
results = await asyncio.gather(task_1(), task_2()) # Runs both tasks concurrently
print(results)
asyncio.run(main())
Explanation:
Now that we have the fundamental understanding of how asynchronus programming works, let's understand how we can implement it in Flask applications with some basic flask app examples:
Asynchronous Database Queries in FlaskFlask's traditional database extensions like Flask-SQLAlchemy are synchronous. To perform asynchronous database operations, we can use Tortoise-ORM, an async ORM for Python.
Let's create a basic Flask app that creates a user table, stores user data and fetches it.
Installation:Flask does not support async routes by default in a WSGI environment, so to keep using async def routes, we need to install Flask with the "async" extra using this command:
pip install "flask[async]"
Install the Tortoise-orm using this command in terminal:
Creating the Application:pip install tortoise-orm aiosqlite
This app wil have features to insert, fetch, and list users asynchronously using Tortoise-ORM.
Python
from flask import Flask, jsonify, request
from tortoise import Tortoise, fields
from tortoise.models import Model
import asyncio
app = Flask(__name__)
# Define an asynchronous User model
class User(Model):
id = fields.IntField(pk=True)
name = fields.CharField(50)
email = fields.CharField(100, unique=True)
# Initialize Tortoise ORM properly
async def init_tortoise():
await Tortoise.init(
db_url="sqlite://db.sqlite3", # Database connection
modules={"models": ["__main__"]} # Register models
)
await Tortoise.generate_schemas() # Create tables
@app.before_request
def initialize():
"""Ensure Tortoise ORM is initialized before handling any request."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(init_tortoise())
# Asynchronous route to create a new user
@app.route('/add-user', methods=['POST'])
async def add_user():
data = request.get_json() # No await here
# If using Tortoise ORM (which is async)
user = await User.create(name=data['name'], email=data['email']) # Use await on async functions
return jsonify({"message": "User created", "user": {"id": user.id, "name": user.name, "email": user.email}})
# Asynchronous route to fetch a user by ID
@app.route('/user/<int:user_id>')
async def get_user(user_id):
user = await User.get_or_none(id=user_id)
if user:
return jsonify({"id": user.id, "name": user.name, "email": user.email})
return jsonify({"error": "User not found"}), 404
# Asynchronous route to fetch all users
@app.route('/users')
async def get_users():
users = await User.all().values("id", "name", "email") # Fetch all users asynchronously
return jsonify(users)
if __name__ == '__main__':
app.run(debug=True)
Code Breakdown:
Adding a user:
1. Run the application using command - python app.py and open Postman Api application to test it.
2. First we need to add a user in the databse, follow these steps to do it:
3. Select POST as the request type.
4. Enter the API URL- http://127.0.0.1:5000/add-user
5. Go to the "Body" Tab, select raw, choose JSON from the dropdown and paste the following in the Body section:
{
"username": "Geek,
"email": "geeks@gfg.org"
}
6. Click send and the user is added in the database.
Adding a userFetching user data:
To fetch the user data, make a get request to the URL - http://127.0.0.1:5000/users
Fetching user data Running Background Tasks in FlaskFlask doesn't natively support background tasks, but we can use asyncio.create_task() for lightweight tasks that run without blocking the main application.
Python
from flask import Flask
import asyncio
app = Flask(__name__)
async def background_task():
await asyncio.sleep(5)
print("Background task completed")
@app.route('/start-task')
def start_task():
asyncio.run(background_task()) # Ensures an event loop runs the task
return {"message": "Task started"}
if __name__ == '__main__':
app.run(debug=True)
Explanation:
1. background_task() – An asynchronous function that waits for 5 seconds before printing a message.
2. start_task() Route
Run the application and open Postman application to make a GET Request on URL- http://127.0.0.1:5000/start-task.
GET RequestAfter making the GET request, we will receive a background task completed message in the terminal after 5 seconds of delay.
Delayed MessageRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4