0
0
Flaskframework~5 mins

Calling tasks asynchronously in Flask

Choose your learning style9 modes available
Introduction

Sometimes, you want your web app to do long jobs without making users wait. Calling tasks asynchronously lets your app start a job and keep working without delay.

Sending emails after a user signs up without making them wait.
Processing uploaded files while letting users continue browsing.
Running reports or data analysis in the background.
Calling external APIs that take time without freezing the app.
Syntax
Flask
from flask import Flask
from flask_mail import Mail, Message
from threading import Thread

app = Flask(__name__)
mail = Mail(app)

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

@app.route('/send-email')
def send_email():
    msg = Message('Hello', sender='you@example.com', recipients=['friend@example.com'])
    msg.body = 'This is an async email.'
    thread = Thread(target=send_async_email, args=(app, msg))
    thread.start()
    return 'Email is being sent!'

Use a separate thread or a task queue to run tasks without blocking the main app.

Make sure to pass the app context if your task needs Flask features.

Examples
This example runs a simple function in a new thread so it doesn't block the main program.
Flask
from threading import Thread

def background_task():
    print('Task running')

thread = Thread(target=background_task)
thread.start()
This shows how to send an email without waiting for it to finish by using a thread.
Flask
from flask import Flask
from flask_mail import Mail, Message
from threading import Thread

app = Flask(__name__)
mail = Mail(app)

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

@app.route('/send-email')
def send_email():
    msg = Message('Hi', sender='you@example.com', recipients=['friend@example.com'])
    msg.body = 'Async email body'
    Thread(target=send_async_email, args=(app, msg)).start()
    return 'Email sent asynchronously!'
Sample Program

This Flask app starts a long task in the background when you visit the home page. The page responds immediately while the task runs.

Flask
from flask import Flask
from threading import Thread
import time

app = Flask(__name__)

def long_task():
    print('Task started')
    time.sleep(5)  # Simulate a long job
    print('Task finished')

@app.route('/')
def index():
    thread = Thread(target=long_task)
    thread.start()
    return 'Long task started, you can keep browsing!'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Using threads is simple but not always best for heavy tasks; consider task queues like Celery for bigger apps.

Always be careful with shared data when using threads to avoid conflicts.

Summary

Asynchronous tasks let your app do long jobs without making users wait.

Use threads or task queues to run tasks in the background.

Remember to handle Flask app context when running tasks outside the main thread.