芹菜(烧瓶)跑步工人/不正确的名字

时间:2017-04-22 17:43:31

标签: python flask celery

我在运行芹菜工人流程时遇到了问题。 我的python代码(test.py):

from flask import *
from celery import *


def main():
    #flask related code
    app = Flask(__name__)
    app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
    app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'

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

    @celery.task
        def my_background_task(arg1, arg2):
            f = open('file.txt','w')
            f.write('answer:'+str(arg1))
            f.close()
            return 1

    @app.route('/createServer', methods=['POST'])
         def createServer():
             task = my_background_task.apply_async(args=["test0", "test1"], countdown=10)
             return jsonify({"status": "done"})

    app.run(host='127.0.0.1', port=8080, debug=True)

if __name__ == "__main__":
    main()

当我使用

运行工作人员时
celery worker -A test --broker=redis://127.0.0.1:6379  --loglevel=info

并插入一个新命令我收到此错误

[2017-04-22 18:02:09,184: ERROR/MainProcess] Received unregistered task of type u'__init__.my_background_task'.
The message has been ignored and discarded.

Did you remember to import the module containing this task?
Or maybe you're using relative imports?

Please see
http://docs.celeryq.org/en/latest/internals/protocol.html
for more information.

The full contents of the message body was:
'[["test0", "test1"], {}, {"chord": null, "callbacks": null, "errbacks": null, "chain": null}]' (93b)
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 559, in on_task_received
    strategy = strategies[type_]
KeyError: u'__init__.my_background_task'

出了什么问题?看来这是因为我的main()处理?知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

worker需要能够从定义它的模块中导入任务函数,这在嵌套在另一个作用域内时是不可能的(在本例中是main函数内部)。

尝试在主要范围内定义任务:

    @celery.task
    def my_background_task(arg1, arg2):
        ...

    def main():
        ...