在django中使用celery
環(huán)境
python models:
- celery-4.1.1
- redis-2.10.6
- django-1.11.7
其他:
- redis-3.2.9
- macos
- python3.6
創(chuàng)建django工程
django-admin startproject dc
cd dc
django-admin startapp main
此時(shí)項(xiàng)目結(jié)構(gòu)如下
dc |-- __init__.py |-- main | |-- __init__.py | |-- admin.py | |-- apps.py | |-- migrations | | `-- __init__.py | |-- models.py | |-- tests.py | `-- views.py |-- settings.py |-- urls.py `-- wsgi.py修改settings.py, 添加app
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','dc.main' //new added ]修改dc/main/models.py, 創(chuàng)建新models
from django.db import models# Create your models here.class Person(models.Model):first_name = models.CharField(max_length=30)last_name = models.CharField(max_length=30)創(chuàng)建根訪問節(jié)點(diǎn)
dc/main/views.py
from django.shortcuts import render from django.http import HttpResponse # Create your views here.def hello(request):return HttpResponse('hello world')dc/urls.py
urlpatterns = [url(r'^admin/', admin.site.urls),url(r'^$', hello) //new added ]依次執(zhí)行以下語(yǔ)句, 初始化django各功能模塊
python manage.py migrate python manage.py makemigrations main python manage.py sqlmigrate main 0001 python manage.py migrate接下來python manage.py runserver, 訪問http://127.0.0.1:8000 即可看到hello world.
啟動(dòng)redis
redis是作為celery中間件使用的, 用來存儲(chǔ)消息隊(duì)列.
redis解壓后, 直接運(yùn)行src/redis-server即可啟動(dòng), 默認(rèn)端口6379
配置celery
參考文檔
創(chuàng)建dc/celery.py
#-*- coding:utf-8 -*-import os from celery import Celery# set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dc.settings')app = Celery('dc')# 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()修改 dc/__init__.py
from .celery import app as celery_app__all__ = ['celery_app']修改 dc/settings.py, 設(shè)定 redis URL
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/3'創(chuàng)建dc/main/tasks.py
#-*- coding:utf-8 -*-from celery import shared_task@shared_task def test():import timetime.sleep(5)from dc.main.models import Personperson = Person(first_name='smith', last_name='jhon')person.save()c = Person.objects.count()print(f'person count is {c}')修改dc/main/views.py
def hello(request):from dc.main.tasks import testtest.delay()return HttpResponse('hello world')啟動(dòng)celery進(jìn)程
celery -A dc worker -l info接下來訪問http://127.0.0.1:8000, 即可發(fā)現(xiàn)頁(yè)面立刻返回, 并沒有被time阻塞, 查看啟動(dòng)celery的窗口, 即可發(fā)現(xiàn)log以及打印的信息, 確定models可以正常使用.
おわり.
總結(jié)
以上是生活随笔為你收集整理的在django中使用celery的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: latex参考文献顺序不对_Latex-
- 下一篇: c语言中的取模运算符_C语言除法算法和取