├── README.md └── myproject ├── db.sqlite3 ├── manage.py ├── myapp ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── tasks.py ├── tests.py └── views.py └── myproject ├── __init__.py ├── celery.py ├── settings.py ├── urls.py └── wsgi.py /README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HaddyYang/django-celery-redis-simple/223927350d1128a8fdd1a3e4a3d108037516a680/README.md -------------------------------------------------------------------------------- /myproject/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HaddyYang/django-celery-redis-simple/223927350d1128a8fdd1a3e4a3d108037516a680/myproject/db.sqlite3 -------------------------------------------------------------------------------- /myproject/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /myproject/myapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HaddyYang/django-celery-redis-simple/223927350d1128a8fdd1a3e4a3d108037516a680/myproject/myapp/__init__.py -------------------------------------------------------------------------------- /myproject/myapp/admin.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from django.contrib import admin 3 | from .models import Blog 4 | 5 | # Register your models here. 6 | @admin.register(Blog) 7 | class BlogAdmin(admin.ModelAdmin): 8 | """blog admin""" 9 | list_display=('id', 'caption') 10 | -------------------------------------------------------------------------------- /myproject/myapp/apps.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class MyappConfig(AppConfig): 7 | name = 'myapp' 8 | -------------------------------------------------------------------------------- /myproject/myapp/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.4 on 2017-05-04 07:14 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='Blog', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ('caption', models.CharField(max_length=30)), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /myproject/myapp/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HaddyYang/django-celery-redis-simple/223927350d1128a8fdd1a3e4a3d108037516a680/myproject/myapp/migrations/__init__.py -------------------------------------------------------------------------------- /myproject/myapp/models.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from __future__ import unicode_literals 3 | from django.db import models 4 | 5 | class Blog(models.Model): 6 | caption = models.CharField(max_length=30) 7 | 8 | def __unicode__(self): 9 | return self.caption 10 | -------------------------------------------------------------------------------- /myproject/myapp/tasks.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from __future__ import absolute_import 3 | from celery.decorators import task 4 | import time 5 | 6 | #异步任务 7 | @task 8 | def sendmail(email): 9 | print('start send email to %s' % email) 10 | time.sleep(5) #休息5秒 11 | print('success') 12 | return True 13 | 14 | #bind等于True则绑定到celery app对象,可使用app的方法 15 | @task(bind=True) 16 | def err_retry(self, email): 17 | try: 18 | a = 1/0 19 | except Exception as e: 20 | #尝试重新执行1次任务 21 | raise self.retry(exc=e) 22 | 23 | 24 | #定时任务 25 | from celery.task.schedules import crontab 26 | from celery.decorators import periodic_task 27 | 28 | #每分钟执行一次 29 | #http://docs.celeryproject.org/en/master/userguide/periodic-tasks.html 30 | @periodic_task(run_every=crontab()) 31 | def some_task(): 32 | print('periodic task test!!!!!') 33 | time.sleep(5) 34 | print('success') 35 | return True -------------------------------------------------------------------------------- /myproject/myapp/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /myproject/myapp/views.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from django.shortcuts import render 3 | from django.http import HttpResponse 4 | 5 | from .models import Blog 6 | from .tasks import sendmail 7 | import json 8 | 9 | def home(request): 10 | #耗时任务,发送邮件 11 | sendmail.delay('test@test.com') 12 | 13 | #其他行为 14 | data = list(Blog.objects.values('caption')) 15 | return HttpResponse(json.dumps(data), content_type = 'application/json') 16 | -------------------------------------------------------------------------------- /myproject/myproject/__init__.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from __future__ import absolute_import, unicode_literals 3 | 4 | #引入celery对象 5 | from .celery import app as celery_app -------------------------------------------------------------------------------- /myproject/myproject/celery.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from __future__ import absolute_import, unicode_literals 3 | 4 | from celery import Celery 5 | from django.conf import settings 6 | import os 7 | 8 | #获取当前文件夹名,即为该Django的项目名 9 | project_name = os.path.split(os.path.abspath('.'))[-1] 10 | project_settings = '%s.settings' % project_name 11 | 12 | #设置环境变量 13 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', project_settings) 14 | 15 | #实例化Celery 16 | app = Celery(project_name) 17 | 18 | #使用django的settings文件配置celery 19 | app.config_from_object('django.conf:settings') 20 | 21 | #Celery加载所有注册的应用 22 | app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) -------------------------------------------------------------------------------- /myproject/myproject/settings.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | """ 3 | Django settings for myproject project. 4 | 5 | Generated by 'django-admin startproject' using Django 1.9.4. 6 | 7 | For more information on this file, see 8 | https://docs.djangoproject.com/en/1.9/topics/settings/ 9 | 10 | For the full list of settings and their values, see 11 | https://docs.djangoproject.com/en/1.9/ref/settings/ 12 | """ 13 | 14 | import os 15 | 16 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 17 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 18 | 19 | 20 | # Quick-start development settings - unsuitable for production 21 | # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ 22 | 23 | # SECURITY WARNING: keep the secret key used in production secret! 24 | SECRET_KEY = '1#jd=eidsqe@5dlveyqz-@d4z5#vig!$yp+9s1c)@ibzn+=jmq' 25 | 26 | # SECURITY WARNING: don't run with debug turned on in production! 27 | DEBUG = True 28 | 29 | ALLOWED_HOSTS = [] 30 | 31 | 32 | # Application definition 33 | 34 | INSTALLED_APPS = [ 35 | 'django.contrib.admin', 36 | 'django.contrib.auth', 37 | 'django.contrib.contenttypes', 38 | 'django.contrib.sessions', 39 | 'django.contrib.messages', 40 | 'django.contrib.staticfiles', 41 | 'myapp', 42 | ] 43 | 44 | MIDDLEWARE_CLASSES = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 51 | 'django.contrib.messages.middleware.MessageMiddleware', 52 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 53 | ] 54 | 55 | ROOT_URLCONF = 'myproject.urls' 56 | 57 | TEMPLATES = [ 58 | { 59 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 60 | 'DIRS': [], 61 | 'APP_DIRS': True, 62 | 'OPTIONS': { 63 | 'context_processors': [ 64 | 'django.template.context_processors.debug', 65 | 'django.template.context_processors.request', 66 | 'django.contrib.auth.context_processors.auth', 67 | 'django.contrib.messages.context_processors.messages', 68 | ], 69 | }, 70 | }, 71 | ] 72 | 73 | WSGI_APPLICATION = 'myproject.wsgi.application' 74 | 75 | 76 | # Database 77 | # https://docs.djangoproject.com/en/1.9/ref/settings/#databases 78 | 79 | DATABASES = { 80 | 'default': { 81 | 'ENGINE': 'django.db.backends.sqlite3', 82 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 83 | } 84 | } 85 | 86 | 87 | # Password validation 88 | # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators 89 | 90 | AUTH_PASSWORD_VALIDATORS = [ 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 99 | }, 100 | { 101 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 102 | }, 103 | ] 104 | 105 | 106 | # Internationalization 107 | # https://docs.djangoproject.com/en/1.9/topics/i18n/ 108 | 109 | LANGUAGE_CODE = 'en-us' 110 | 111 | TIME_ZONE = 'UTC' 112 | 113 | USE_I18N = True 114 | 115 | USE_L10N = True 116 | 117 | USE_TZ = True 118 | 119 | 120 | # Static files (CSS, JavaScript, Images) 121 | # https://docs.djangoproject.com/en/1.9/howto/static-files/ 122 | 123 | STATIC_URL = '/static/' 124 | 125 | #celery settings 126 | #celery中间人 redis://redis服务所在的ip地址:端口/数据库 127 | BROKER_URL = 'redis://localhost:6379/0' 128 | #celery结果返回,可用于跟踪结果 129 | CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' 130 | #celery内容等消息的格式设置 131 | CELERY_ACCEPT_CONTENT = ['application/json',] 132 | CELERY_TASK_SERIALIZER = 'json' 133 | CELERY_RESULT_SERIALIZER = 'json' 134 | #celery时区设置,使用settings中TIME_ZONE同样的时区 135 | CELERY_TIMEZONE = TIME_ZONE 136 | -------------------------------------------------------------------------------- /myproject/myproject/urls.py: -------------------------------------------------------------------------------- 1 | """myproject URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url 17 | from django.contrib import admin 18 | from myapp.views import home 19 | 20 | urlpatterns = [ 21 | url(r'^admin/', admin.site.urls), 22 | url(r'^$', home, name='home') 23 | ] 24 | -------------------------------------------------------------------------------- /myproject/myproject/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for myproject project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") 15 | 16 | application = get_wsgi_application() 17 | --------------------------------------------------------------------------------