2017-04-26 47 views
0

我想爲我的應用程序使用芹菜在燒瓶中製成,但我得到以下錯誤「在請求上下文之外工作」。這聽起來像我試圖在前端發出請求之前訪問請求對象,但我無法弄清楚什麼是錯誤的。我很感激你是否可以讓我知道問題是什麼。瓶子拋出'在請求上下文之外工作'。

[2017-04-26 13:33:04,940: INFO/MainProcess] Received task: app.result[139a2679-e9df-49b9-ab42-1f53a09c01fd] 
[2017-04-26 13:33:06,168: ERROR/PoolWorker-2] Task app.result[139a2679-e9df-49b9-ab42-1f53a09c01fd] raised unexpected: RuntimeError('Working outside of request context.\n\nThis typically means that you attempted to use functionality that needed\nan active HTTP request. Consult the documentation on testing for\ninformation about how to avoid this problem.',) 
Traceback (most recent call last): 
    File "/Library/Python/2.7/site-packages/celery/app/trace.py", line 367, in trace_task 
    R = retval = fun(*args, **kwargs) 
    File "/Users/Pooneh/projects/applications/ray_tracer_app_flask/flask_celery.py", line 14, in __call__ 
    return TaskBase.__call__(self, *args, **kwargs) 
    File "/Library/Python/2.7/site-packages/celery/app/trace.py", line 622, in __protected_call__ 
    return self.run(*args, **kwargs) 
    File "/Users/Pooneh/projects/applications/ray_tracer_app_flask/app.py", line 33, in final_result 
    light_position = request.args.get("light_position", "(0, 0, 0)", type=str) 
    File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 343, in __getattr__ 
    return getattr(self._get_current_object(), name) 
    File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 302, in _get_current_object 
    return self.__local() 
    File "/Library/Python/2.7/site-packages/flask/globals.py", line 37, in _lookup_req_object 
    raise RuntimeError(_request_ctx_err_msg) 
RuntimeError: Working outside of request context. 

This typically means that you attempted to use functionality that needed 
an active HTTP request. Consult the documentation on testing for 
information about how to avoid this problem. 

app.py

app = Flask(__name__) 
app.config.update(CELERY_BROKER_URL = 'amqp://localhost//', 
CELERY_RESULT_BACKEND='amqp://localhost//') 

celery = make_celery(app) 


@app.route('/') 
def my_form(): 
    return render_template("form.html") 

@app.route('/result') 
def result(): 
    final_result.delay() 
    return "celery!" 

@celery.task(name='app.result') 
def final_result(): 
    light_position = request.args.get("light_position", "(0, 0, 0)", type=str) 
    light_position_coor = re.findall("[-+]?\d*\.\d+|[-+]?\d+", light_position) 
    x = float(light_position_coor[0]) 
    y = float(light_position_coor[1]) 
    z = float(light_position_coor[2]) 

    encoded = base64.b64encode(open("/Users/payande/projects/applications/app_flask/static/pic.png", "rb").read()) 
    return jsonify(data=encoded) 

回答

1

芹菜任務由後臺工作外異步HTTP請求(這是使用它們的他們的主要好處之一)的運行,所以你不能訪問request任務內的對象。

您可以將數據傳遞給任務的參數,而不是:

final_result.delay(request.args.get("light_position")) 

@celery.task(name='app.result') 
def final_result(light_position): 
    ... 

當然,這也意味着任務的返回值不能在HTTP響應中使用(由於任務可以後完成響應已經發送)。

相關問題