kanban-app/backend/app/celery/__init__.py

74 lines
2.1 KiB
Python
Raw Normal View History

2026-02-21 18:38:19 +00:00
"""
Celery application factory for the Crafting Shop application.
Follows the same application factory pattern as Flask.
"""
from celery import Celery
from flask import Flask
def make_celery(app: Flask) -> Celery:
"""
Create and configure a Celery application with Flask context.
Args:
app: Flask application instance
Returns:
Configured Celery application instance.
"""
# Create Celery app with Flask app name
celery_app = Celery(
app.import_name,
broker=app.config["CELERY"]["broker_url"],
backend=app.config["CELERY"]["result_backend"]
)
# Update configuration from Flask config
celery_app.conf.update(app.config["CELERY"])
# Set up Flask application context for tasks
# This ensures tasks have access to Flask extensions (db, etc.)
class ContextTask(celery_app.Task):
"""Celery task that runs within Flask application context."""
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery_app.Task = ContextTask
# Auto-discover tasks in the tasks module
celery_app.autodiscover_tasks(['app.celery.tasks'])
# Configure Beat schedule
from .beat_schedule import configure_beat_schedule
configure_beat_schedule(celery_app)
# Import tasks to ensure they're registered
from .tasks import example_tasks
print(f"✅ Celery configured with broker: {celery_app.conf.broker_url}")
print(f"✅ Celery configured with backend: {celery_app.conf.result_backend}")
print(f"✅ Beat schedule configured with {len(celery_app.conf.beat_schedule)} tasks")
return celery_app
# Global Celery instance
celery = None
def init_celery(app: Flask) -> Celery:
"""
Initialize the global celery instance with Flask app.
This should be called in create_app() after Flask app is created.
Args:
app: Flask application instance
Returns:
Configured Celery application instance
"""
global celery
celery = make_celery(app)
return celery