0
0
Flaskframework~5 mins

Celery integration overview in Flask

Choose your learning style9 modes available
Introduction

Celery helps your Flask app do tasks in the background. This means your app stays fast and doesn't wait for slow jobs to finish.

You want to send emails without making users wait.
You need to process large files without slowing down the app.
You want to run tasks regularly, like cleaning up old data.
You want to handle tasks that take time, like image resizing.
You want to keep your app responsive while doing heavy work.
Syntax
Flask
from celery import Celery

celery_app = Celery('app_name', broker='redis://localhost:6379/0')

@celery_app.task
def background_task():
    # your code here
    pass
The broker is where Celery gets tasks from, often Redis or RabbitMQ.
Use @celery_app.task to mark functions as background tasks.
Examples
This example creates a simple task that adds two numbers in the background.
Flask
from celery import Celery

celery_app = Celery('myapp', broker='redis://localhost:6379/0')

@celery_app.task
def add(x, y):
    return x + y
Shows how to connect Celery with a Flask app and define a task to send emails.
Flask
from flask import Flask
from celery import Celery

app = Flask(__name__)
celery_app = Celery(app.name, broker='redis://localhost:6379/0')

@celery_app.task
def send_email(email):
    print(f"Sending email to {email}")
Sample Program

This Flask app has a route to reverse text in the background using Celery. When you send a POST request with JSON {"text": "hello"}, it starts the task and returns a task ID immediately.

Flask
from flask import Flask, request, jsonify
from celery import Celery

app = Flask(__name__)
celery_app = Celery(app.name, broker='redis://localhost:6379/0')

@celery_app.task
def reverse_text(text):
    return text[::-1]

@app.route('/reverse', methods=['POST'])
def reverse():
    data = request.json
    task = reverse_text.delay(data['text'])
    return jsonify({'task_id': task.id}), 202
OutputSuccess
Important Notes

Make sure Redis or your broker is running before starting Celery.

Use task.delay() to run tasks asynchronously.

Check task results with Celery's result backend if needed.

Summary

Celery lets Flask apps run slow tasks in the background.

Use a broker like Redis to manage tasks.

Mark functions with @celery_app.task to make them background jobs.