描述
嗨,我正在学习Celery,我读了一篇博客。>> Celery and the Flask Application Factory Pattern - miguelgrinberg.com
所以我写了一个小程序,用Celery运行Flask
代码
应用.__初始化__。PY
from flask import Flask
from celery import Celery
celery = Celery(__name__, broker='amqp://127.0.0.1:5672/')
def create_app():
app = Flask(__name__)
@celery.task
def add(x, y):
print x+y
@app.route('/')
def index():
add.delay(1, 3)
return 'Hello World!'
return app
manage.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
celery_worker_1.py
from app import celery, create_app()
f_app = create_app()
f_app.app_context().push()
celery_worker_2.py
from app import celery, create_app
@celery.task
def foo():
print 'Balabala...'
f_app = create_app()
f_app.app_context().push()
问题
当我运行Flask服务器和芹菜使用时:
celery -A celery_worker_1 worker -l
Celery引发NotRegistered错误:
Traceback (most recent call last): File "D:\Python27\lib\site-packages\billiard\pool.py", line 363, in workloop
result = (True, prepare_result(fun(*args, **kwargs))) File "D:\Python27\lib\site-packages\celery\app\trace.py", line 349, in
_fast_trace_task
return _tasks[task].__trace__(uuid, args, kwargs, request)[0] File "D:\Python27\lib\site-packages\celery\app\registry.py", line 26, in __missing__
raise self.NotRegistered(key) NotRegistered: 'app.add'
但不是使用celery_worker_2:
celery -A celery_worker_2 worker -l info
任务正确运行:
[2015-11-28 15:45:56,299: INFO/MainProcess] Received task: app.add[cbe5e1d6-c5df-4141-9db1-e6313517c202]
[2015-11-28 15:45:56,302: WARNING/Worker-1] 4
[2015-11-28 15:45:56,371: INFO/MainProcess] Task app.add[cbe5e1d6-c5df-4141-9db1-e6313517c202] succeeded in 0.0699999332428s: None
为什么Celery可以使用celery_worker_1的代码正确运行?
PS:我不擅长英语,你可以指出我,如果你不能理解,我想再次描述一下。谢谢!的