celery-No-result-backend-is-configured

NotImplementedError: No-result-backend-is-configured.

头像
逆旅 2022-10-30T20:09:35

mycelery.py

import time
from app import celery
@celery.task            #使用异步任务装饰器task
def add(x, y):
    time.sleep(5)       #休眠5秒
    return x + y

app.py

from flask import Flask
import tasks
from mycelery import make_celery
from celery.result import AsyncResult

app = Flask(__name__)
celery = make_celery(app)               #调用make_celery方法并传入app使celery和app进行关联

@app.route('/')
def hello():
    result=tasks.add.delay(1,2)                #调用tasks文件中的add()异步任务方法
    return f'任务ID:{result.id}'

@app.route('/<id>')
def get_task(id:str):
    result = AsyncResult(id=id)
    return str(result.get())

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

获取任务ID时,一直报错

Traceback (most recent call last):
  File "/Users/gynl/opt/anaconda3/envs/spider/lib/python3.8/site-packages/flask/app.py", line 2548, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/gynl/opt/anaconda3/envs/spider/lib/python3.8/site-packages/flask/app.py", line 2528, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/gynl/opt/anaconda3/envs/spider/lib/python3.8/site-packages/flask/app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/gynl/opt/anaconda3/envs/spider/lib/python3.8/site-packages/flask/app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/gynl/opt/anaconda3/envs/spider/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/gynl/opt/anaconda3/envs/spider/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/Volumes/数据/program/python/mhSpider/app.py", line 17, in get_task
    return str(result.get())
  File "/Users/gynl/opt/anaconda3/envs/spider/lib/python3.8/site-packages/celery/result.py", line 224, in get
    return self.backend.wait_for_pending(
  File "/Users/gynl/opt/anaconda3/envs/spider/lib/python3.8/site-packages/celery/backends/base.py", line 756, in wait_for_pending
    meta = self.wait_for(
  File "/Users/gynl/opt/anaconda3/envs/spider/lib/python3.8/site-packages/celery/backends/base.py", line 1087, in _is_disabled
    raise NotImplementedError(E_NO_BACKEND.strip())
NotImplementedError: No result backend is configured.
Please see the documentation for more information.

解决办法:


@app.route('/<id>')
def get_task(id:str):
    result = AsyncResult(id=id)
    return str(result.get())
##改为
@app.route('/<id>')
def get_task(id:str):
    result = celery.AsyncResult(id=id)
    return str(result.get())
最后修改: 2022-10-30T20:09:35

版权声明:署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)

comment 评论

验证图片
评论
仿 Valine