我一直在设置 django-celery 的测试实例并浏览了一些基本的 celery 示例,并遇到了一些看起来很奇怪的东西。
我首先在这里浏览了“Django 的第一步”芹菜页面:http: //docs.celeryproject.org/en/latest/django/first-steps-with-django.html
一切正常,标准 celery 教程前几节中的基本示例也是如此。
python manage.py 外壳
一旦我开始在 Django shell 中尝试一些画布原语,我就会得到一个 NameError,如下所示:
$ python manage.py shell
In [1]: from celerytest.tasks import add
In [2]: from celery import group
In [3]: group(add.s(i, i) for i in xrange(10))().get()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/Users/jacinda/envs/testproj/lib/python2.7/site-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 group(add.s(i, i) for i in xrange(10))().get()
/Users/jacinda/envs/testproj/lib/python2.7/site-packages/celery/canvas.pyc in __call__(self, *partial_args, **options)
397
398 def __call__(self, *partial_args, **options):
--> 399 tasks = [task.clone() for task in self.tasks]
400 if not tasks:
401 return
/Users/jacinda/envs/testproj/lib/python2.7/site-packages/celery/utils/functional.pyc in __iter__(self)
286
287 def __iter__(self): # needed for Python 2.5
--> 288 return iter(self.data)
/Users/jacinda/envs/testproj/lib/python2.7/site-packages/kombu/utils/__init__.pyc in __get__(self, obj, type)
292 return obj.__dict__[self.__name__]
293 except KeyError:
--> 294 value = obj.__dict__[self.__name__] = self.__get(obj)
295 return value
296
/Users/jacinda/envs/testproj/lib/python2.7/site-packages/celery/utils/functional.pyc in data(self)
283 @cached_property
284 def data(self):
--> 285 return list(self.__it)
286
287 def __iter__(self): # needed for Python 2.5
/Users/jacinda/envs/testproj/lib/python2.7/site-packages/django/core/management/commands/shell.pyc in <genexpr>((i,))
----> 1 group(add.s(i, i) for i in xrange(10))().get()
NameError: global name 'add' is not defined
但是下一行有效:
In [4]: add.delay(2,2).get()
Out[4]: 4
与明确列出子任务一样:
In [5]: group([add.s(1,2), add.s(3,4)])().get()
Out[5]: [3, 7]
蟒蛇
如果我使用常规 Python shell 并手动导入设置而不是使用 manage.py shell,一切正常。IE
$ ipython
In [1]: from testproj import settings
In [2]: from celerytest.tasks import add
In [3]: from celery import group
In [4]: group(add.s(i, i) for i in xrange(10))().get()
Out[4]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
我用 epdb 查看了失败的案例,但无法弄清楚到底发生了什么。
我已经用谷歌搜索了这个,我发现的唯一 100% 类似的参考是 celery 的 github 页面上的这个问题:https ://github.com/celery/celery/issues/1222 。海报提到了我遇到的同样问题,但只说他的“Python/Django shell 正在做一些奇怪的事情”,并没有进一步详细说明。关于导致这种情况的任何想法,或者我应该在其他地方寻找什么?