Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Celery using Flask application factory pattern

I am having issues with implementing celery with python flask application factory app

I have intend creating an instance of the Celery app from the app init file as below:

from celery import Celery
celery = Celery('myapp', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0')

I can't use Celery from other blueprint when called.

like image 286
Peter Ewanfo Avatar asked Sep 02 '26 01:09

Peter Ewanfo


2 Answers

def init_celery(app):
    celery = Celery()
    celery.conf.broker_url = app.config['CELERY_BROKER_URL']
    celery.conf.result_backend = app.config['CELERY_RESULT_BACKEND']
    celery.conf.update(app.config)

    class ContextTask(celery.Task):
        """Make celery tasks work with Flask app context"""
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    return celery

Initizialize celery when create_app:

init_celery(app)

Find how celery is implemented in this Flask cookiecutter

like image 106
Joost Döbken Avatar answered Sep 04 '26 16:09

Joost Döbken


The answer by Joost Döbken may work but it seems a bit more complicated than it has to be.

I found simpler solution by Miguel Grinberg that works great for me:

from celery import Celery
from config import config, Config

celery = Celery(__name__, broker=Config.CELERY_BROKER_URL)

def create_app(config_name):
    # ...
    celery.conf.update(app.config)
    # ...
    return app

https://blog.miguelgrinberg.com/post/celery-and-the-flask-application-factory-pattern

like image 31
MBT Avatar answered Sep 04 '26 14:09

MBT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!