python Flask RuntimeError:在请求上下文之外工作

时间:2017-03-30 23:18:41

标签: python celery

我查看了所有相关问题,但找不到我想要的东西。 我有一个烧瓶应用app.py,其中还包括芹菜任务

from flask import Flask, request, current_app
from celery import Celery
from mongoalchemy.session import Session
from PIL import Image
from model import the_data

app = Flask(__name__)
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'

celery = Celery('app', broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

@celery.task
def process_image():
    with app.app_context():
        session = Session.connect('mydb')
        session.clear_collection(the_data)
        image = Image.open(request.files['file'])
        ### do something ###

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' in request.files:
            process_image.delay()
    return 'Processing image...'

if __name__ == '__main__':
    app.run(debug=True, port=8008)

简而言之,app.py将从其他脚本接收通过requests.post发送的图像文件,并将其传递到队列以便使用芹菜进行处理。

我使用app.app_context()作为我发现的RuntimeError: Working outside of request context的解决方案,但不幸的是,即使我编辑了代码,错误仍然存​​在。

我该怎么做才能解决这类错误?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

looks like你可以通过将* args和** kwargs作为参数包含在delay调用中来传递给你的任务。将文件传递给process_image功能。这不起作用的原因是您在上下文之外访问请求。一旦return 'Processing image...'执行该上下文关闭。

编辑:基本上,从我链接到的文档中可以看出,您可以在process_image函数中添加参数并在delay调用中将其传递给它。这是未经测试的,因此可能需要一些调整。

@celery.task
def process_image(file=None):        
    if file is None:
        return False
    image = Image.open(file)
        ### do something ###

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' in request.files:
            process_image.delay(request.files['file'])
    return 'Processing image...'
相关问题