【问题标题】:Database is not updated in Celery task with Flask and SQLAlchemy使用 Flask 和 SQLAlchemy 在 Celery 任务中未更新数据库
【发布时间】:2015-11-24 01:04:37
【问题描述】:

我正在使用 Flask 和 SQLAlchemy 编写 Web 应用程序。我的程序需要在后台处理一些东西,然后在数据库中将这些东西标记为已处理。使用standard Flask/Celery example,我有这样的事情:

from flask import Flask
from celery import Celery

def make_celery(app):
    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task
    class ContextTask(TaskBase):
        abstract = True
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery


app = Flask(__name__)

celery = make_celery(app)

class Stuff(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    processed = db.Column(db.Boolean)


@celery.task()
def process_stuff(stuff):
    # process stuff here

    stuff.processed = True
    db.session.commit()

@app.route("/process_stuff/<id>")
def do_process_stuff(id):
    stuff = Stuff.query.get_or_404(id)
    process_stuff.delay(stuff)
    return redirect(url_for("now_wait"))

我可以从process_stuff 访问我的数据库(例如,提交类似Stuff.query.get(some_id) 工作的查询),但db.session.commit() 什么也不做:我的stuff 记录没有更新。根据 Celery 工作日志,提交发生但数据库中没有任何变化。我的db.session.commit() 有问题吗?是否有可能以某种方式做出这样的提交?

【问题讨论】:

    标签: python flask sqlalchemy celery


    【解决方案1】:

    好的,我明白了。传递给process_stuff()stuff 未附加到db.session。我必须在process_stuff() 中明确请求才能获得正确的stuff 对象,如下所示:

    @celery.task()
    def process_stuff(stuff):
        # process stuff here
    
        my_stuff = Stuff.query.get(stuff.id)
    
        my_stuff.processed = True
        db.session.commit()
    

    现在可以了。

    【讨论】:

      猜你喜欢
      • 2012-08-16
      • 2017-12-15
      • 1970-01-01
      • 2020-11-02
      • 2017-07-07
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      相关资源
      最近更新 更多