Celery延迟任务中的SQLAlchemy会话处理 [英] SQLAlchemy session handling in delayed Celery tasks
问题描述
我正在通过SQLAlchemy使用关系数据库.我想产生一个使用Celery处理数据库的工作.有一个代码:
I am using a relational database via SQLAlchemy. I want to spawn a job that deals with databases using Celery. There is a code:
from sqlalchemy.orm.session import Session
from celery.task import task
from myapp.user import User
@task
def job(user):
# job...
session = Session.object_session(user)
with user.begin():
user.value = result_value
def ordinary_web_request_handler(uid):
assert isinstance(session, Session)
user = session.query(User).get(int(uid))
# deals with user...
job.delay(user)
return response
我需要在延迟的 job
中使用SQLAlchemy会话,但是还没有 session
.如何将会话设置为传递的 user
实体?
I need to use a SQLAlchemy session in the delayed job
, but there’s no session
yet. How can I set a session into passed user
entity?
我有很多想法,但是我不确定哪种方法(或没有一种方法)是最佳实践:
There are ways I thought, but I am not sure which of these (or none of these) is the best practice:
- 始终仅传递主键,并通过传递的主键检索新实例.
- 设置传递的实例的会话(但我不知道如何).
- 请勿在延迟的任务中使用ORM.
推荐答案
You should be able to initiate your session with the worker signals: http://celery.readthedocs.org/en/latest/userguide/signals.html#worker-signals
如果您使用类似单例的模式来确保在该线程中始终有可用的会话,那么一切都会正常进行.
If you use a singleton-like pattern to make sure you always have a session available in that thread than everything should work just fine.
这篇关于Celery延迟任务中的SQLAlchemy会话处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!