简体   繁体   English

从烧瓶视图中分离芹菜任务分离SQLAlchemy实例(DetachedInstanceError)

[英]pushing celery task from flask view detach SQLAlchemy instances (DetachedInstanceError)

I am using SQLAlchemy models (derived from sqlalchemy.ext.declarative.declarative_base) together with Flask-SQLAlchemy 我正在使用SQLAlchemy模型(从sqlalchemy.ext.declarative.declarative_base派生)和Flask-SQLAlchemy

When I try to run any celery task (just empty) 当我尝试运行任何芹菜任务(只是空)

@celery.task()
def empty_task():
    pass

in common flask view 在常见的烧瓶视图中

@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, ...}

i get 我明白了

DetachedInstanceError: Instance <Image at 0x7f6d67e37b50> is not bound to a Session; attribute refresh operation cannot proceed

when I trying access model after task push. 当我在任务推送后尝试访问模型时。 Without task it works fine. 没有任务它工作正常。 How to fix it? 怎么解决?

update: celery use this task base: 更新:芹菜使用此任务库:

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

ah my mistake in running task. 啊我在运行任务时的错误。 it should be empty_task.apply_async() 它应该是empty_task.apply_async()

calling it directly it creates new app context with new session causing closing old one. 直接调用它会创建新的应用程序上下文与新会话导致关闭旧的会话。

Today I had the same issue while I was running my nose tests. 今天我在进行鼻子测试时遇到了同样的问题。

DetachedInstanceError: Instance <EdTests at 0x1071c4790> is not bound to a Session; attribute refresh operation cannot proceed

I am using Celery and Flask SQLAlchemy. 我正在使用Celery和Flask SQLAlchemy。 Issue was caused when I changed in testing settings: 我在测试设置中更改时导致问题:

CELERY_ALWAYS_EAGER = True

I had found that when running celery tasks synchronously db session is closed at the end of the task. 我发现在同步运行celery任务时,db session会在任务结束时关闭。

I solved my issue following Celery's documentation user guide. 我在Celery的文档用户指南后解决了我的问题。 Celery recommends not to enable eager testing of tasks. Celery建议不要对任务进行急切的测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM