Skip to content

How to ensure each request has it's own db.session in flask-sqlalchemy app using celery and postgresql and being run by gunicorn? #1386

Answered by shawnim
shawnim asked this question in Q&A
Discussion options

You must be logged in to vote

For Celery worker db sessions I used this in myapp/__init__.py:

def celery_init_app(app: Flask) -> Celery:
    class FlaskDatabaseTask(Task):
        def __init__(self):
            self.sessions = {}

        def __call__(self, *args: object, **kwargs: object) -> object:
            with app.app_context():
                return super().__call__(*args, **kwargs)

        def before_start(self, task_id, args, kwargs):
            with app.app_context():
                CelerySession = sessionmaker(bind=db.engine)
                session = CelerySession()
                self.sessions[task_id] = session
            super().before_start(task_id, args, kwargs)

        def after_return(self,…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by shawnim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant