简体   繁体   English

Python、Celery、Flask,“在应用程序上下文之外工作”

[英]Python, Celery, Flask, "working outside of application context"

I am trying to schedule tasks using Celery and Python for a Flask app.我正在尝试使用 Celery 和 Python 为 Flask 应用程序安排任务。 I basically want to run a function in another directory every x amount of time and make it a celery task.我基本上想每隔 x 时间在另一个目录中运行一个函数,并使其成为 celery 任务。 I import the function test_check and I try and put it under a celery task called testcheck(), however, I get the error:我导入函数 test_check 并尝试将它放在名为 testcheck() 的 celery 任务下,但是,出现错误:

working outside of application context在应用程序上下文之外工作

How can I fix this?我怎样才能解决这个问题? Here is my setup:这是我的设置:

from app import app
from celery import Celery
from datetime import timedelta
from app.mod_check.views import test_check

celery = Celery(__name__,
             broker='amqp://guest:@localhost/',
             backend='amqp://guest:@localhost/'
             )

celery.config_from_object(__name__)

@celery.task
def add(x, y):
    print "celery working!"
    return x + y

@celery.task
def testcheck():
        test_check()

CELERYBEAT_SCHEDULE = {
    'add-every-30-seconds': {
        'task': 'tasks2.testcheck',
        'schedule': timedelta(seconds=5),
        #'args': (16, 16)
    },
}

CELERY_TIMEZONE = 'Europe/London'

Whatever test_check is, it does something that needs a request context.无论test_check是什么,它都会做一些需要请求上下文的事情。 Since Celery tasks are not part of the HTTP request/response cycle, you need to set up a request context manually.由于 Celery 任务不是 HTTP 请求/响应周期的一部分,因此您需要手动设置请求上下文。

with app.test_request_context():
    test_check()

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

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