人生苦短,我用python。
看到这句话的时候,感觉可能确实是很深得人心,不过每每想学学,就又止步,年纪大了,感觉学什么东西都很慢,很难,精神啊注意力啊思维啊都跟不上。今天奶牛来分享自己今天踩的一个坑。
先说说配置过程吧,初学Django,啥都不懂,当然,python也很水,啥东西都得现查现用。Django安装还是很简单的。
apt-get install python3pip3 install django
嗯,就是两条命令的事儿。
再说celery的安装:
pip3 install celerypip3 install redis==2.10.6
目前奶牛所在的时间redis for python的版本是redis-3.0.1,为什么要用2.10.6呢?因为3.0.1压根配置就无法运行!!!
继续安装redis server
apt-get install redisservice redis start
然后就可以按照celery的官方教程走了,放个URL:http://docs.celeryproject.org/en/latest/django/index.html
python3 manage.py startproject nenewcd nenewpython3 manage.py startapp nenewapptouch ./nenew/celery.pytouch ./nenewapp/tasks.py
然后增加nenew/nenew/celery.py内容为
from __future__ import absolute_import, unicode_literalsimport osfrom celery import Celery# set the default Django settings module for the 'celery' program.os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nenew.settings')app = Celery('nenew')# Using a string here means the worker doesn't have to serialize# the configuration object to child processes.# - namespace='CELERY' means all celery-related configuration keys# should have a `CELERY_` prefix.app.config_from_object('django.conf:settings', namespace='CELERY')# Load task modules from all registered Django app configs.app.autodiscover_tasks()@app.task(bind=True)def debug_task(self): print('Request: {0!r}'.format(self.request))
增加nenew/nenew/__init__.py的内容
from __future__ import absolute_import, unicode_literals# This will make sure the app is always imported when# Django starts so that shared_task will use this app.from .celery import app as celery_app__all__ = ('celery_app',)
增加nenew/nenewtest/tasks.py的内容
# Create your tasks herefrom __future__ import absolute_import, unicode_literalsfrom celery import shared_task@shared_taskdef add(x, y): return x + y@shared_taskdef mul(x, y): return x * y@shared_taskdef xsum(numbers): return sum(numbers)
在nenew/nenew/settings.py中增加和修改
...ALLOWED_HOSTS = ['*']....INSTALLED_APPS = [... 'nenewtest',]...CELERY_BROKER_URL = 'redis://localhost:6379/1'CELERY_RESULT_BACKEND = ‘redis://localhost:6379/0'
在nenew/nenewtest/views.py中增加或修改为
from django.shortcuts import renderfrom django.http import HttpResponsefrom .tasks import add# Create your views here.def nenewtest(request): result = add.delay('2','2') result.ready() return HttpResponse('nenew Django Celery worker run !')
新闻热点
疑难解答