[英]Database is not updated in Celery task with Flask and SQLAlchemy
[英]pushing celery task from flask view detach SQLAlchemy instances (DetachedInstanceError)
我正在使用SQLAlchemy模型(从sqlalchemy.ext.declarative.declarative_base派生)和Flask-SQLAlchemy
当我尝试运行任何芹菜任务(只是空)
@celery.task()
def empty_task():
pass
在常见的烧瓶视图中
@blueprint.route(...)
def view():
image = Image(...)
db.session.add(image)
db.session.flush()
#this cause later error
empty_task()
#now accessing attributes ends with DetachedInstanceError
return jsonify({'name': image.name, ...}
我明白了
DetachedInstanceError: Instance <Image at 0x7f6d67e37b50> is not bound to a Session; attribute refresh operation cannot proceed
当我在任务推送后尝试访问模型时。 没有任务它工作正常。 怎么解决?
更新:芹菜使用此任务库:
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
try:
return TaskBase.__call__(self, *args, **kwargs)
except Exception:
sentry.captureException()
raise
celery.Task = ContextTask
啊我在运行任务时的错误。 它应该是empty_task.apply_async()
直接调用它会创建新的应用程序上下文与新会话导致关闭旧的会话。
今天我在进行鼻子测试时遇到了同样的问题。
DetachedInstanceError: Instance <EdTests at 0x1071c4790> is not bound to a Session; attribute refresh operation cannot proceed
我正在使用Celery和Flask SQLAlchemy。 我在测试设置中更改时导致问题:
CELERY_ALWAYS_EAGER = True
我发现在同步运行celery任务时,db session会在任务结束时关闭。
我在Celery的文档用户指南后解决了我的问题。 Celery建议不要对任务进行急切的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.