SQLAlchemy session issues with celery

谁说我不能喝 提交于 2019-12-03 03:09:20

I believe the problem is that you are attempting to use the SQLAlchemy session in your Celery task.

The first thing I recommend doing is creating two separate scoped sessions, one for your Celery application and another one for your web application. Next, I would make sure your Celery database session is only configured once during Celery initialization. You can use the Celery worker_init.connect to make sure it creates the database during Celery startup (http://hynek.me/articles/using-celery-with-pyramid/).

It is very important that your web application does not use the same database session as your Celery application.

Something like this for your tasks.py file:

from celery import Celery
from celery.signals import worker_init
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

Session = sqlalchemy.orm.scoped_session(
    sqlalchemy.orm.sessionmaker(autocommit=True, autoflush=True))


@worker_init.connect
def initialize_session():
    some_engine = create_engine('database_url')    
    Session.configure(bind=some_engine)

@celery.task
def rerun_scheduler():
    log.info("Starting pipeline scheduler")
    webapp.sheduledtask.service.check_for_updates(Session)
    log.info("Ending pipeline scheduler")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!