小编Clé*_*ner的帖子

如何在没有全局变量的芹菜任务中设置sqlalchemy会话

简介:我想在celery任务中使用sqlalchemy会话,而不需要包含该会话的全局变量.

我在一个芹菜任务的项目中使用SQLAlchemy,而我正在使用它

Currently, I have a global variable 'session' defined along with my celery app setup (celery.py), with a worker signal to set it up.

session = scoped_session(sessionmaker())

@celeryd_init.connect
def configure_workers(sender=None, conf=None, **kwargs):
    # load the application configuration
    # db_uri = conf['db_uri']
    engine = create_engine(db_uri)
    session.configure(bind=engine)
Run Code Online (Sandbox Code Playgroud)

In the module defining the tasks, I simply import 'session' and use it. Tasks are defined with a custom class that closes the session after returning:

class DBTask(Task):
    def after_return(self, *args, **kwargs):
        session.remove()
Run Code Online (Sandbox Code Playgroud)

That …

python sqlalchemy celery

8
推荐指数
1
解决办法
5837
查看次数

标签 统计

celery ×1

python ×1

sqlalchemy ×1