简介:我想在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 …