Django, Flask, FastAPI integration patterns for Celery. Use when integrating Celery with Django, Flask, or FastAPI, setting up framework-specific configurations, handling application contexts, managing database transactions with tasks, configuring async workers, or when user mentions Django Celery, Flask Celery, FastAPI background tasks, framework integration, or web framework task queues.
Limited to specific tools
Additional assets for this skill
This skill is limited to using the following tools:
examples/django-complete-setup.mdexamples/fastapi-async.mdexamples/flask-factory-pattern.mdscripts/setup-framework.shscripts/test-integration.shscripts/validate-framework.shtemplates/django-integration/__init__.pytemplates/django-integration/celery.pytemplates/django-integration/settings.pytemplates/django-integration/tasks.pytemplates/fastapi-background.pytemplates/fastapi-integration/celery_app.pytemplates/fastapi-integration/main.pytemplates/fastapi-integration/tasks.pytemplates/flask-context.pytemplates/flask-integration/celery_app.pytemplates/flask-integration/tasks.pytemplates/transaction-safe-django.pyPurpose: Integrate Celery with Django, Flask, and FastAPI using framework-specific patterns and best practices.
Activation Triggers:
Key Resources:
templates/django-integration/ - Django app structure with Celerytemplates/flask-integration/ - Flask factory pattern with Celerytemplates/fastapi-integration/ - FastAPI async integrationtemplates/transaction-safe-django.py - Django transaction handlingtemplates/fastapi-background.py - FastAPI BackgroundTasks vs Celerytemplates/flask-context.py - Flask app context in tasksscripts/test-integration.sh - Test framework integrationscripts/validate-framework.sh - Validate framework setupexamples/ - Complete integration examplesCore Setup:
pip install celery django-celery-beat django-celery-results
myproject/
├── myproject/
│ ├── __init__.py
│ ├── celery.py # Celery app configuration
│ ├── settings.py # Django settings with Celery config
│ └── urls.py
├── myapp/
│ ├── tasks.py # Task definitions
│ └── views.py # Views that call tasks
└── manage.py
# Copy Django integration template
cp -r templates/django-integration/* /path/to/project/
Key Patterns:
Transaction-Safe Tasks:
templates/transaction-safe-django.pytransaction.on_commit() to delay task executionDjango ORM in Tasks:
CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = TrueConfiguration:
CELERY_BROKER_URL in settings.pyCELERY_RESULT_BACKEND for task resultsdjango-celery-beat for periodic tasks (admin UI)django-celery-results to store results in Django DBCore Setup:
pip install celery flask
myapp/
├── __init__.py # Flask app factory
├── celery.py # Celery app with Flask context
├── tasks.py # Task definitions
├── views.py # Routes
└── config.py # Configuration
# Copy Flask integration template
cp -r templates/flask-integration/* /path/to/project/
Key Patterns:
Application Context:
templates/flask-context.pyapp.app_context() for database/config accessFactory Pattern:
Configuration:
CELERY_BROKER_URL from app.configCore Setup:
pip install celery fastapi uvicorn
app/
├── main.py # FastAPI app
├── celery_app.py # Celery configuration
├── tasks.py # Task definitions
├── routers/
│ └── api.py # API routes
└── config.py # Settings
# Copy FastAPI integration template
cp -r templates/fastapi-integration/* /path/to/project/
Key Patterns:
Async Tasks:
.delay() or .apply_async() from sync contextasyncio.create_task() for FastAPI BackgroundTasksBackgroundTasks vs Celery:
templates/fastapi-background.pyDependency Injection:
Configuration:
app.state for shared resources (if needed)Problem: "Lost connection to MySQL/Postgres during task"
Solution:
# Close connections before task runs (Django)
from django.db import connection
connection.close()
# Or configure connection pooling
CELERY_BROKER_POOL_LIMIT = None # Unlimited
DATABASES = {
'default': {
'CONN_MAX_AGE': 0, # Close after request
}
}
Problem: "Working outside of application context" (Flask)
Solution:
# Use context template
from templates.flask_context import make_celery
celery = make_celery(app)
# Or manually push context
@celery.task
def my_task():
with app.app_context():
# Access db, config, etc.
pass
Problem: Task runs before database commit (Django)
Solution:
# Use on_commit
from django.db import transaction
def my_view(request):
obj = MyModel.objects.create(name="test")
transaction.on_commit(
lambda: process_object.delay(obj.id)
)
Problem: "Cannot call async function from sync context" (FastAPI)
Solution:
# Celery task (sync or async)
@celery.task
async def process_data(data):
# Can use async here
result = await some_async_function(data)
return result
# FastAPI endpoint (async)
@app.post("/process")
async def process(data: dict):
# Call Celery from async context
task = process_data.delay(data)
return {"task_id": task.id}
# Check integration is configured correctly
./scripts/validate-framework.sh django
./scripts/validate-framework.sh flask
./scripts/validate-framework.sh fastapi
Checks:
# Run integration tests
./scripts/test-integration.sh django
./scripts/test-integration.sh flask
./scripts/test-integration.sh fastapi
Tests:
CRITICAL: Never hardcode credentials in integration code
✅ CORRECT:
# Django settings.py
CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL', 'redis://your_redis_url_here')
# Flask config.py
CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL', 'redis://your_redis_url_here')
# FastAPI config.py
class Settings(BaseSettings):
celery_broker_url: str = "redis://your_redis_url_here"
class Config:
env_file = ".env"
❌ WRONG:
CELERY_BROKER_URL = "redis://actual-password@redis.example.com"
CELERY_BROKER_URL = "amqp://user:real_password@rabbitmq"
Always:
your_redis_url_here.env to .gitignoretemplates/django-integration/templates/transaction-safe-django.pyexamples/django-complete-setup.mdtemplates/flask-integration/templates/flask-context.pyexamples/flask-factory-pattern.mdtemplates/fastapi-integration/templates/fastapi-background.pyexamples/fastapi-async.md| Framework | Context Needed | Transaction Safe | Async Support |
|---|---|---|---|
| Django | Auto | Use on_commit | Via celery |
| Flask | Manual push | N/A | Via celery |
| FastAPI | Not needed | N/A | Native |
| Package | Purpose | Required For |
|---|---|---|
django-celery-beat | Periodic tasks UI | Django admin scheduling |
django-celery-results | Store results in DB | Django result persistence |
flask | Web framework | Flask integration |
fastapi[all] | Async web framework | FastAPI integration |
Supported Frameworks: Django 4+, Flask 2+, FastAPI 0.100+ Celery Version: 5.3+ Python: 3.9+