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.
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.
from celery import Celery celery_app = Celery('app_name', broker='redis://localhost:6379/0') @celery_app.task def background_task(): # your code here pass
broker is where Celery gets tasks from, often Redis or RabbitMQ.@celery_app.task to mark functions as background tasks.from celery import Celery celery_app = Celery('myapp', broker='redis://localhost:6379/0') @celery_app.task def add(x, y): return x + y
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}")
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.
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
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.
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.
@celery_app.task decorator.@celery_app.task
def multiply(x, y):
return x * y
result = multiply.delay(3, 4)
print(result.get())
What will be printed?multiply.delay(3, 4) sends the task to Celery to run asynchronously.result.get() waits for the task to finish and returns the output, which is 3 * 4 = 12.@celery_app.task def add(x, y): return x + yBut when you call
add.delay(2, 3), it raises an IndentationError. What is the problem?return x + y is not indented, causing IndentationError.@celery_app.task, and are called with delay().Pass the test and this pattern moves unknown