ehf*_*eng 2 python celery flask celery-task
在文档中,@celery.task 装饰器没有传递参数,但在 GitHub 示例中,它被命名为“tasks.add”。为什么?当我删除名称时,该示例不再有效,抱怨
KeyError: '__main__.add'
[1] http://flask.pocoo.org/docs/0.10/patterns/celery/ [2] https://github.com/thrisp/flask-celery-example/blob/master/app.py#L25
在 Flask 文档中,未设置任务name,因为假定代码位于tasks模块内部,因此任务名称将自动生成为tasks.add, 在 Celery 文档中:
每个任务必须有一个唯一的名称,如果未提供自定义名称,将从函数名称生成新名称
检查Celery 文档的名称部分以获取更多信息。
在 Github 上的另一个示例中,作者明确设置了名称,而不是依赖于自动命名,如果__main__.tasks作为主模块运行,则运行 Flask 服务器时就会出现这种情况。
更新一下您遇到此问题的原因:
hello_world当您/test通过传递x和访问页面时,该任务将从函数发送y:
res = add.apply_async((x, y))
Run Code Online (Sandbox Code Playgroud)
因为任务add位于__main__模块内部,所以它将被命名__main__.add并发送到具有此名称的工作程序,但另一方面,您开始使用的工作程序:
celery worker -A app.celery
Run Code Online (Sandbox Code Playgroud)
是否已注册此任务,因为app.add这就是您收到此错误的原因:
[2014-10-10 10:32:29,540: ERROR/MainProcess] Received unregistered task of type '__main__.add'.
The message has been ignored and discarded.
Did you remember to import the module containing this task?
Or maybe you are using relative imports?
Please see http://docs.celeryq.org/en/latest/userguide/tasks.html#task-names for more information.
The full contents of the message body was:
{'timelimit': (None, None), 'utc': True, 'chord': None, 'args': (2787476, 36096995), 'retries': 0, 'expires': None, 'task': '__main__.add', 'callbacks': None, 'errbacks': None, 'taskset': None, 'kwargs': {}, 'eta': None, 'id': '804e10a0-2569-4338-a5e3-f9e07689d1d1'} (218b)
Traceback (most recent call last):
File "/home/peter/env/celery/lib/python2.7/site-packages/celery/worker/consumer.py", line 455, in on_task_received
strategies[name](message, body,
KeyError: '__main__.add'
Run Code Online (Sandbox Code Playgroud)
检查worker的输出:
[tasks]
. app.add
. celery.backend_cleanup
. celery.chain
. celery.chord
. celery.chord_unlock
. celery.chunks
. celery.group
. celery.map
. celery.starmap
Run Code Online (Sandbox Code Playgroud)
Celery仅将任务名称发送给worker来执行它,因此当您显式设置任务名称时,该函数hello_world将发送在worker中注册的具有该名称的任务。
更新:
任务名称可以是您想要的任何名称,也可以是add,并且您的 celery 任务根本不必位于模块中tasks,要了解有关任务名称的更多信息,请尝试以下操作:
删除显式任务名称并启动工作人员:
celery worker -A app.celery
Run Code Online (Sandbox Code Playgroud)
在另一个终端窗口中,cd转到代码目录并启动交互式 python shell 并尝试以下操作:
>>> import app
>>> app
<module 'app' from 'app.pyc'>
>>> app.add
<@task: app.add of app:0xb6a29a6c>
>>> # check the name of the task
... app.add.name
'app.add'
>>> t = app.add.delay(2, 3)
>>> t.result
5
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我们没有使用显式名称,并且它按预期工作,因为我们发送任务的名称与工作程序中注册的名称相同(见上文)。
现在回到为什么在删除任务名称时出现此错误,任务是从app.py右侧发送的,在同一目录中运行以下命令:
$ python -i app.py
Run Code Online (Sandbox Code Playgroud)
Ctrl然后使用+中断 Flask 服务器C,并尝试以下操作:
>>> add.name
'__main__.add'
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这就是您收到此错误的原因,而不是因为您删除了任务名称。
| 归档时间: |
|
| 查看次数: |
2369 次 |
| 最近记录: |