python - 使用 Flask 和 SQLAlchemy 的 Celery 任务中的数据库未更新

标签 python flask sqlalchemy celery

我正在使用 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 worker 日志,发生了提交,但数据库没有任何变化。我的 db.session.commit() 有问题吗?是否有可能以某种方式做出这样的 promise ?

最佳答案

好的,我明白了。传递给 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()

现在可以了。

关于python - 使用 Flask 和 SQLAlchemy 的 Celery 任务中的数据库未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33883714/

相关文章:

python - 如何为 TensorFlow 变量赋值?

python - 访问父类中的子类实例

python - 使用 python 脚本登录 azure cli 时出现问题

python - Netbeans 8.2 Python 插件

python - 浏览器不解释我的 CSS

python - SQLAlchemy - 模型 - 使用动态字段 - ActiveRecord

php - 在 Python 中使用 flask 进行 Hmac 验证(在 PHP 和 RUBY 中有引用)

python - flask 在运行时不读取 bootstrap.css (mac)

python - python中的统一码

python - 有向图 - SQLAlchemy ORM