前言: 針對高延時任務, 直接在一次網絡請求中處理完畢會致使很很差的體驗, celery則能夠不阻塞請求後臺處理這些任務, 而且能夠 使用django的models進行數據庫操做.
python models:html
其餘:python
django-admin startproject dc
cd dc
django-admin startapp main
redis
此時項目結構以下sql
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
, 建立新modelsmacos
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)
建立根訪問節點django
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.pysession
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', hello) //new added ]
依次執行如下語句, 初始化django各功能模塊app
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.
redis是做爲celery中間件使用的, 用來存儲消息隊列.
redis解壓後, 直接運行src/redis-server
便可啓動, 默認端口6379
建立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
, 設定 redis URL
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/3'
建立dc/main/tasks.py
#-*- coding:utf-8 -*- from celery import shared_task @shared_task def test(): import time time.sleep(5) from dc.main.models import Person person = 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 test test.delay() return HttpResponse('hello world')
啓動celery進程
celery -A dc worker -l info
接下來訪問http://127.0.0.1:8000
, 便可發現頁面馬上返回, 並無被time阻塞, 查看啓動celery的窗口, 便可發現log以及打印的信息, 肯定models能夠正常使用.
おわり.