Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Flask Templates
  • Jinja2
  • Flask-REST API
  • Python SQLAlchemy
  • Flask Bcrypt
  • Flask Cookies
  • Json
  • Postman
  • Django
  • Flask Projects
  • Flask Interview Questions
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJs
  • Vue.Js
Open In App
Next Article:
Flask Asynchronous Programming Using async.io
Next article icon

Flask Asynchronous Programming Using async.io

Last Updated : 01 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • Making external API calls
  • Processing large datasets
  • Managing real-time communication

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 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 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:

  • async def: Declares a function as asynchronous, meaning it can perform non-blocking operations.
  • await: Suspends execution of the function until the awaited task completes, preventing blocking.

Running Multiple Async Tasks

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:

  • async def functions must be awaited inside another async function.
  • await asyncio.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 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:

pip install tortoise-orm aiosqlite

Creating the Application:

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:

  • User Model: Defines an async User model with fields for id, name, and unique email.
  • Database Initialization: init_tortoise() function asynchronously connects to an SQLite database and generates schemas.
  • Before Request Hook: initialize() function uses an event loop to run init_tortoise() before handling requests.
  • /add-user Route: Accepts JSON input and creates a new user asynchronously, then returns the user details.
  • /user/int:user_id Route: Asynchronously fetches a user by ID; returns user data if found or a 404 error otherwise.
  • /users Route: Retrieves all users asynchronously and returns them as a JSON list.

Running and Testing the Application

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": "[email protected]"
}


6. Click send and the user is added in the database.

Async1
Adding a user

Fetching user data:

To fetch the user data, make a get request to the URL - http://127.0.0.1:5000/users

Async2
Fetching user data

Running Background Tasks in Flask

Flask 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

  • Creates a new event loop.
  • Uses executor.submit() to run background_task() without blocking Flask.
  • Returns a response immediately while the task runs in the background.

Run the application and open Postman application to make a GET Request on URL- http://127.0.0.1:5000/start-task.

Async3
GET Request

After making the GET request, we will receive a background task completed message in the terminal after 5 seconds of delay.

Async4
Delayed Message

Next Article
Flask Asynchronous Programming Using async.io

P

prajjqv52
Improve
Article Tags :
  • Python
  • Python Flask
Practice Tags :
  • python

Similar Reads

    Python Tornado - Asynchronous Networking
    Traditional synchronous networking models often struggle to keep pace with the demands of modern applications. Enter Tornado-Asynchronous networking, a paradigm-shifting approach that leverages non-blocking I/O to create lightning-fast, highly scalable network applications. In this article, we will
    4 min read
    Asynchronous HTTP Requests with Python
    Performing multiple HTTP requests is needed while working with applications related to data preprocessing and web development. In the case of dealing with a large number of requests, using synchronous requests cannot be so efficient because each request must wait for the previous request to get comp
    4 min read
    Asyncio Vs Threading In Python
    In Python, both Asyncio and Threading are used to achieve concurrent execution. However, they have different mechanisms and use cases. This article provides an in-depth comparison between Asyncio and Threading, explaining their concepts, key differences, and practical applications.Table of ContentKe
    6 min read
    Periodically Execute a Function with asyncio in Tornado
    The primary benefit is improved performance. Asynchronous programming allows your application to efficiently handle tasks that may block the main thread, such as network operations or I/O-bound tasks. This can lead to better responsiveness and scalability. Also by controlling the frequency of period
    4 min read
    Python's Equivalent of JavaScript Promises
    When we work with JavaScript, we often use Promises to handle asynchronous tasks. A Promise is like a promise in real life - it guarantees something will happen in the future. Python doesn't have Promises. In Python, handling asynchronous tasks is a bit different from JavaScript. We can use asyncio,
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences