Flaskis inherentlysynchronous, meaning each request is processed one at a time. However, modern web applications often require handling multiple tasks simultaneously, such as:
- Making external API calls
- Processing large datasets
- Managing real-time communication
Asynchronous programming allows us to execute multiple tasksconcurrently, improving performance and responsiveness.
With Python's built-inasyncio, we can introduce asynchronous behavior in Flask applications, allowing tasks like database queries andAPI requests to run without blocking the main application thread.
Features of asynchronous programming
- Improves Performance – Handles multiple tasks without waiting for each to complete.
- Non-Blocking I/O – Ideal for tasks like fetching external data or database operations.
- Better User Experience – Reduces delays for users when making API requests.
Syntax of async.io Programs
Before using async.io in Flask, let’s understand how asynchronous functions work in Python.
Declaring an Asynchronous Function
In Python, asynchronous functions are defined using theasync defkeyword:
Pythonimportasyncioasyncdefmy_async_function():print("Task started")awaitasyncio.sleep(2)# Simulates an async operationprint("Task completed")# Running the async functionasyncio.run(my_async_function())
Explanation:
- async def: Declares a function asasynchronous, meaning it can perform non-blocking operations.
- await: Suspends execution of the function until theawaited task completes, preventing blocking.
Running Multiple Async Tasks
To run multiple async functions concurrently, useasyncio.gather():
Pythonasyncdeftask_1():awaitasyncio.sleep(2)return"Task 1 Complete"asyncdeftask_2():awaitasyncio.sleep(3)return"Task 2 Complete"asyncdefmain():results=awaitasyncio.gather(task_1(),task_2())# Runs both tasks concurrentlyprint(results)asyncio.run(main())
Explanation:
- async def functions must be awaited inside another async function.
- awaitasyncio.sleep(n) simulates non-blocking behavior.
- asyncio.gather() executes multiple async functions in parallel.
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 Flask
Flask's traditional database extensions likeFlask-SQLAlchemy are synchronous. To perform asynchronous database operations, we can useTortoise-ORM, an asyncORMfor 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 aWSGI 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:
pip install tortoise-orm aiosqlite
Creating the Application:
This app wil have features to insert, fetch, and list users asynchronously using Tortoise-ORM.
PythonfromflaskimportFlask,jsonify,requestfromtortoiseimportTortoise,fieldsfromtortoise.modelsimportModelimportasyncioapp=Flask(__name__)# Define an asynchronous User modelclassUser(Model):id=fields.IntField(pk=True)name=fields.CharField(50)email=fields.CharField(100,unique=True)# Initialize Tortoise ORM properlyasyncdefinit_tortoise():awaitTortoise.init(db_url="sqlite://db.sqlite3",# Database connectionmodules={"models":["__main__"]}# Register models)awaitTortoise.generate_schemas()# Create tables@app.before_requestdefinitialize():"""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'])asyncdefadd_user():data=request.get_json()# No await here# If using Tortoise ORM (which is async)user=awaitUser.create(name=data['name'],email=data['email'])# Use await on async functionsreturnjsonify({"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>')asyncdefget_user(user_id):user=awaitUser.get_or_none(id=user_id)ifuser:returnjsonify({"id":user.id,"name":user.name,"email":user.email})returnjsonify({"error":"User not found"}),404# Asynchronous route to fetch all users@app.route('/users')asyncdefget_users():users=awaitUser.all().values("id","name","email")# Fetch all users asynchronouslyreturnjsonify(users)if__name__=='__main__':app.run(debug=True)
Code Breakdown:
- User Model: Defines an async User model with fields forid,name, andunique email.
- Database Initialization:init_tortoise() function asynchronously connects to anSQLitedatabase and generates schemas.
- Before Request Hook:initialize() function uses an event loop to runinit_tortoise() before handling requests.
- /add-user Route: AcceptsJSONinput and creates a new user asynchronously, then returns the user details.
- /user/int:user_id Route: Asynchronouslyfetchesa user byID; returns user data if found or a 404 errorotherwise.
- /users Route: Retrieves all usersasynchronouslyand returns them as aJSON list.
Running and Testing the Application
Adding a user:
1. Run the application using command -python app.py and openPostman Api application to test it.
2. First we need toadd a user in thedatabse, follow these steps to do it:
3. SelectPOSTas 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 dataRunning Background Tasks in Flask
Flask doesn't natively support background tasks, but we can useasyncio.create_task() for lightweight tasks that run without blocking the main application.
PythonfromflaskimportFlaskimportasyncioapp=Flask(__name__)asyncdefbackground_task():awaitasyncio.sleep(5)print("Background task completed")@app.route('/start-task')defstart_task():asyncio.run(background_task())# Ensures an event loop runs the taskreturn{"message":"Task started"}if__name__=='__main__':app.run(debug=True)
Explanation:
1. background_task()– An asynchronous function thatwaits for 5 secondsbefore printing a message.
2. start_task() Route
- Creates a new event loop.
- Usesexecutor.submit() to runbackground_task() without blocking Flask.
- Returns a response immediately while the task runs in the background.
Run the application and openPostmanapplication to make aGETRequest 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 after5 seconds of delay.
Delayed Message