2015-05-20 160 views
1

我用我的SQLAlchemy模型(從sqlalchemy.ext.declarative.declarative_base派生)連同燒瓶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 

回答

1

啊我的錯誤中正在運行的任務。它應該是 empty_task.apply_async()

直接調用它創建新的應用程序上下文與新會話導致關閉舊的。

0

今天我在運行鼻子測試時遇到了同樣的問題。

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

我正在使用芹菜和Flask SQLAlchemy。當我在測試設置中更改 問題是造成:

CELERY_ALWAYS_EAGER = True 

我已經發現,芹菜運行任務時,同步DB會話是在任務結束時關閉。

我按照Celery's documentation用戶指南解決了我的問題。 Celery建議不要對任務進行急切的測試。