├── .gitignore ├── README.md ├── django_celery_project ├── __init__.py ├── asgi.py ├── celery.py ├── settings.py ├── urls.py └── wsgi.py ├── mainapp ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ └── __init__.py ├── models.py ├── tasks.py ├── tests.py ├── urls.py └── views.py ├── manage.py └── send_mail_app ├── __init__.py ├── admin.py ├── apps.py ├── migrations └── __init__.py ├── models.py ├── tasks.py ├── tests.py └── views.py /.gitignore: -------------------------------------------------------------------------------- 1 | /static/** 2 | !/static 3 | __pycache__ 4 | .vscode 5 | db.sqlite3 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Everything about using Celery with Django. 2 | 3 | Link for video tutorial - https://www.youtube.com/playlist?list=PLLz6Bi1mIXhHKA1Szy2aj9Jbs6nw9fhNY -------------------------------------------------------------------------------- /django_celery_project/__init__.py: -------------------------------------------------------------------------------- 1 | from .celery import app as celery_app 2 | 3 | __all__ = ('celery_app',) -------------------------------------------------------------------------------- /django_celery_project/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for django_celery_project project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_celery_project.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /django_celery_project/celery.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, unicode_literals 2 | import os 3 | 4 | from celery import Celery 5 | from django.conf import settings 6 | from celery.schedules import crontab 7 | 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_celery_project.settings') 9 | 10 | app = Celery('django_celery_project') 11 | app.conf.enable_utc = False 12 | 13 | app.conf.update(timezone = 'Asia/Kolkata') 14 | 15 | app.config_from_object(settings, namespace='CELERY') 16 | 17 | # Celery Beat Settings 18 | app.conf.beat_schedule = { 19 | 'send-mail-every-day-at-8': { 20 | 'task': 'send_mail_app.tasks.send_mail_func', 21 | 'schedule': crontab(hour=0, minute=46, day_of_month=19, month_of_year = 6), 22 | #'args': (2,) 23 | } 24 | 25 | } 26 | 27 | # Celery Schedules - https://docs.celeryproject.org/en/stable/reference/celery.schedules.html 28 | 29 | app.autodiscover_tasks() 30 | 31 | @app.task(bind=True) 32 | def debug_task(self): 33 | print(f'Request: {self.request!r}') -------------------------------------------------------------------------------- /django_celery_project/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for django_celery_project project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.4. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-%gz^-#%cn#k$r45lbhj)y-($qso#zc3eju2f9ql1z*x-%ilm+v' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 41 | 'mainapp', 42 | 'django_celery_results', 43 | 'django_celery_beat', 44 | 'send_mail_app' 45 | ] 46 | 47 | MIDDLEWARE = [ 48 | 'django.middleware.security.SecurityMiddleware', 49 | 'django.contrib.sessions.middleware.SessionMiddleware', 50 | 'django.middleware.common.CommonMiddleware', 51 | 'django.middleware.csrf.CsrfViewMiddleware', 52 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 53 | 'django.contrib.messages.middleware.MessageMiddleware', 54 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 55 | ] 56 | 57 | ROOT_URLCONF = 'django_celery_project.urls' 58 | 59 | TEMPLATES = [ 60 | { 61 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 62 | 'DIRS': [], 63 | 'APP_DIRS': True, 64 | 'OPTIONS': { 65 | 'context_processors': [ 66 | 'django.template.context_processors.debug', 67 | 'django.template.context_processors.request', 68 | 'django.contrib.auth.context_processors.auth', 69 | 'django.contrib.messages.context_processors.messages', 70 | ], 71 | }, 72 | }, 73 | ] 74 | 75 | WSGI_APPLICATION = 'django_celery_project.wsgi.application' 76 | 77 | 78 | # Database 79 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 80 | 81 | DATABASES = { 82 | 'default': { 83 | 'ENGINE': 'django.db.backends.sqlite3', 84 | 'NAME': BASE_DIR / 'db.sqlite3', 85 | } 86 | } 87 | 88 | 89 | # Password validation 90 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 91 | 92 | AUTH_PASSWORD_VALIDATORS = [ 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 104 | }, 105 | ] 106 | 107 | 108 | # Internationalization 109 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 110 | 111 | LANGUAGE_CODE = 'en-us' 112 | 113 | TIME_ZONE = 'UTC' #Asia/Kolkata 114 | 115 | USE_I18N = True 116 | 117 | USE_L10N = True 118 | 119 | USE_TZ = True 120 | 121 | 122 | # Static files (CSS, JavaScript, Images) 123 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 124 | 125 | STATIC_URL = '/static/' 126 | 127 | # Default primary key field type 128 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 129 | 130 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 131 | 132 | 133 | # CELERY SETTINGS 134 | 135 | CELERY_BROKER_URL = 'redis://127.0.0.1:6379' 136 | CELERY_ACCEPT_CONTENT = ['application/json'] 137 | CELERY_RESULT_SERIALIZER = 'json' 138 | CELERY_TASK_SERIALIZER = 'json' 139 | CELERY_TIMEZONE = 'Asia/Kolkata' 140 | 141 | CELERY_RESULT_BACKEND = 'django-db' 142 | 143 | #CELERY BEAT 144 | CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' 145 | 146 | # SMTP Settings 147 | EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" 148 | EMAIL_USE_TLS = True 149 | EMAIL_HOST = "smtp.gmail.com" 150 | EMAIL_PORT = 587 151 | EMAIL_HOST_USER ='priyanshuguptacontact@gmail.com' 152 | EMAIL_HOST_PASSWORD = "cgdjtyuzsqcuorfi" 153 | DEFAULT_FROM_EMAIL = 'Celery ' 154 | 155 | #cgdjtyuzsqcuorfi -------------------------------------------------------------------------------- /django_celery_project/urls.py: -------------------------------------------------------------------------------- 1 | """django_celery_project URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/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: path('', 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: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from django.urls.conf import include 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | path('', include('mainapp.urls')), 23 | ] 24 | -------------------------------------------------------------------------------- /django_celery_project/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for django_celery_project 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/3.2/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', 'django_celery_project.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /mainapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/priyanshu2015/celery-with-django/cd653f05b6c2a1d1cb3810ed0b9303f8243b64d2/mainapp/__init__.py -------------------------------------------------------------------------------- /mainapp/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /mainapp/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class MainappConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'mainapp' 7 | -------------------------------------------------------------------------------- /mainapp/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/priyanshu2015/celery-with-django/cd653f05b6c2a1d1cb3810ed0b9303f8243b64d2/mainapp/migrations/__init__.py -------------------------------------------------------------------------------- /mainapp/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /mainapp/tasks.py: -------------------------------------------------------------------------------- 1 | from celery import shared_task 2 | 3 | @shared_task(bind=True) 4 | def test_func(self): 5 | #operations 6 | for i in range(10): 7 | print(i) 8 | return "Done" -------------------------------------------------------------------------------- /mainapp/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /mainapp/urls.py: -------------------------------------------------------------------------------- 1 | 2 | from django.urls import path 3 | from django.urls.conf import include 4 | from . import views 5 | urlpatterns = [ 6 | path('', views.test, name="test"), 7 | path('sendmail/', views.send_mail_to_all, name="sendmail"), 8 | path('schedulemail/', views.schedule_mail, name="schedulemail"), 9 | ] 10 | -------------------------------------------------------------------------------- /mainapp/views.py: -------------------------------------------------------------------------------- 1 | from celery.schedules import crontab 2 | from django.http.response import HttpResponse 3 | from django.shortcuts import render 4 | from .tasks import test_func 5 | from send_mail_app.tasks import send_mail_func 6 | from django_celery_beat.models import PeriodicTask, CrontabSchedule 7 | import json 8 | # Create your views here. 9 | def test(request): 10 | test_func.delay() 11 | return HttpResponse("Done") 12 | 13 | def send_mail_to_all(request): 14 | send_mail_func.delay() 15 | return HttpResponse("Sent") 16 | 17 | def schedule_mail(request): 18 | schedule, created = CrontabSchedule.objects.get_or_create(hour = 1, minute = 34) 19 | task = PeriodicTask.objects.create(crontab=schedule, name="schedule_mail_task_"+"5", task='send_mail_app.tasks.send_mail_func')#, args = json.dumps([[2,3]])) 20 | return HttpResponse("Done") 21 | 22 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_celery_project.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /send_mail_app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/priyanshu2015/celery-with-django/cd653f05b6c2a1d1cb3810ed0b9303f8243b64d2/send_mail_app/__init__.py -------------------------------------------------------------------------------- /send_mail_app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /send_mail_app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class SendMailAppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'send_mail_app' 7 | -------------------------------------------------------------------------------- /send_mail_app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/priyanshu2015/celery-with-django/cd653f05b6c2a1d1cb3810ed0b9303f8243b64d2/send_mail_app/migrations/__init__.py -------------------------------------------------------------------------------- /send_mail_app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /send_mail_app/tasks.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth import get_user_model 2 | 3 | from celery import shared_task 4 | from django.core.mail import send_mail 5 | from django_celery_project import settings 6 | from django.utils import timezone 7 | from datetime import timedelta 8 | 9 | @shared_task(bind=True) 10 | def send_mail_func(self): 11 | users = get_user_model().objects.all() 12 | #timezone.localtime(users.date_time) + timedelta(days=2) 13 | for user in users: 14 | mail_subject = "Hi! Celery Testing" 15 | message = "If you are liking my content, please hit the like button and do subscribe to my channel" 16 | to_email = user.email 17 | send_mail( 18 | subject = mail_subject, 19 | message=message, 20 | from_email=settings.EMAIL_HOST_USER, 21 | recipient_list=[to_email], 22 | fail_silently=True, 23 | ) 24 | return "Done" -------------------------------------------------------------------------------- /send_mail_app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /send_mail_app/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | --------------------------------------------------------------------------------