Background processing lets your app do slow tasks without making users wait. It keeps the app fast and smooth.
0
0
Why background processing matters in Flask
Introduction
Sending emails after a user signs up
Processing large files uploaded by users
Running reports that take a long time
Calling external services that respond slowly
Cleaning up old data without blocking users
Syntax
Flask
from flask import Flask, request from threading import Thread app = Flask(__name__) def background_task(arg1): # Do slow work here print(f"Processing {arg1} in background") @app.route('/start') def start(): arg = request.args.get('arg', 'default') thread = Thread(target=background_task, args=(arg,)) thread.start() return 'Task started!'
Use Thread to run tasks in the background without blocking the main app.
Background tasks should not access request data directly after the request ends.
Examples
This example sends an email in the background so the app stays responsive.
Flask
from threading import Thread def send_email(email): print(f"Sending email to {email}") thread = Thread(target=send_email, args=("user@example.com",)) thread.start()
This runs a slow task without stopping the app from working.
Flask
from threading import Thread def long_task(): import time time.sleep(5) print("Task done") Thread(target=long_task).start()
Sample Program
This Flask app starts a background task to greet a user after a delay. The web response is immediate, so the user doesn't wait.
Flask
from flask import Flask, request from threading import Thread app = Flask(__name__) def background_task(name): import time time.sleep(3) # Simulate slow work print(f"Hello, {name}! Task finished.") @app.route('/greet') def greet(): user = request.args.get('user', 'Guest') Thread(target=background_task, args=(user,)).start() return f"Hi {user}, your greeting will be ready soon!" if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Background tasks help keep your app fast and responsive.
Use threads or task queues depending on how complex your background work is.
Always avoid accessing request data inside background tasks after the request ends.
Summary
Background processing lets slow tasks run without blocking users.
Use threads in Flask for simple background jobs.
This improves user experience by keeping the app responsive.