Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9094331
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T23:19:31+00:00 2026-06-16T23:19:31+00:00

I recently switch to Celery 3.0. Before that I was using Flask-Celery in order

  • 0

I recently switch to Celery 3.0. Before that I was using Flask-Celery in order to integrate Celery with Flask. Although it had many issues like hiding some powerful Celery functionalities but it allowed me to use the full context of Flask app and especially Flask-SQLAlchemy.

In my background tasks I am processing data and the SQLAlchemy ORM to store the data. The maintainer of Flask-Celery has dropped support of the plugin. The plugin was pickling the Flask instance in the task so I could have full access to SQLAlchemy.

I am trying to replicate this behavior in my tasks.py file but with no success. Do you have any hints on how to achieve this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T23:19:33+00:00Added an answer on June 16, 2026 at 11:19 pm

    Update: We’ve since started using a better way to handle application teardown and set up on a per-task basis, based on the pattern described in the more recent flask documentation.

    extensions.py

    import flask
    from flask.ext.sqlalchemy import SQLAlchemy
    from celery import Celery
    
    class FlaskCelery(Celery):
    
        def __init__(self, *args, **kwargs):
    
            super(FlaskCelery, self).__init__(*args, **kwargs)
            self.patch_task()
    
            if 'app' in kwargs:
                self.init_app(kwargs['app'])
    
        def patch_task(self):
            TaskBase = self.Task
            _celery = self
    
            class ContextTask(TaskBase):
                abstract = True
    
                def __call__(self, *args, **kwargs):
                    if flask.has_app_context():
                        return TaskBase.__call__(self, *args, **kwargs)
                    else:
                        with _celery.app.app_context():
                            return TaskBase.__call__(self, *args, **kwargs)
    
            self.Task = ContextTask
    
        def init_app(self, app):
            self.app = app
            self.config_from_object(app.config)
    
    
    celery = FlaskCelery()
    db = SQLAlchemy()
    

    app.py

    from flask import Flask
    from extensions import celery, db
    
    def create_app():
        app = Flask()
        
        #configure/initialize all your extensions
        db.init_app(app)
        celery.init_app(app)
    
        return app
    

    Once you’ve set up your app this way, you can run and use celery without having to explicitly run it from within an application context, as all your tasks will automatically be run in an application context if necessary, and you don’t have to explicitly worry about post-task teardown, which is an important issue to manage (see other responses below).

    Troubleshooting

    Those who keep getting with _celery.app.app_context(): AttributeError: 'FlaskCelery' object has no attribute 'app' make sure to:

    1. Keep the celery import at the app.py file level. Avoid:

    app.py

    from flask import Flask
    
    def create_app():
        app = Flask()
    
        initiliaze_extensions(app)
    
        return app
    
    def initiliaze_extensions(app):
        from extensions import celery, db # DOOMED! Keep celery import at the FILE level
        
        db.init_app(app)
        celery.init_app(app)
    
    1. Start you celery workers BEFORE you flask run and use
    celery worker -A app:celery -l info -f celery.log
    

    Note the app:celery, i.e. loading from app.py.

    You can still import from extensions to decorate tasks, i.e. from extensions import celery.

    Old answer below, still works, but not as clean a solution

    I prefer to run all of celery within the application context by creating a separate file that invokes celery.start() with the application’s context. This means your tasks file doesn’t have to be littered with context setup and teardowns. It also lends itself well to the flask ‘application factory’ pattern.

    extensions.py

    from from flask.ext.sqlalchemy import SQLAlchemy
    from celery import Celery
    
    db = SQLAlchemy()
    celery = Celery()
    

    tasks.py

    from extensions import celery, db
    from flask.globals import current_app
    from celery.signals import task_postrun
    
    @celery.task
    def do_some_stuff():
        current_app.logger.info("I have the application context")
        #you can now use the db object from extensions
    
    @task_postrun.connect
    def close_session(*args, **kwargs):
        # Flask SQLAlchemy will automatically create new sessions for you from 
        # a scoped session factory, given that we are maintaining the same app
        # context, this ensures tasks have a fresh session (e.g. session errors 
        # won't propagate across tasks)
        db.session.remove()
    

    app.py

    from extensions import celery, db
    
    def create_app():
        app = Flask()
        
        #configure/initialize all your extensions
        db.init_app(app)
        celery.config_from_object(app.config)
    
        return app
    

    RunCelery.py

    from app import create_app
    from extensions import celery
    
    app = create_app()
    
    if __name__ == '__main__':
        with app.app_context():
            celery.start()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I recently had to rewrite our rest api, and made the switch from Flask
I recently had to switch from using Microsofts SQL server to using MySQL. The
I've been using jshint with node but just recently had to switch over to
I've recently tried to switch my app engine app to using openID, but I'm
I've recently had to switch encoding of webapp I'm working on from ISO-xx to
I was recently told to stop using mysql_query() and instead switch to mysqli() .
Recently I switch from using LWP::UserAgent to LWPx::ParanoidAgent to fetch URLs provided by 3rd
Recently I made the switch from using asmx web services to using wcf services,
I've recently learned that python doesn't have the switch/case statement. I've been reading about
My company has recently decided to switch to GitHub from Assembla (using git). How

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.