Skip to content

Commit 8e09e0c

Browse files
author
Siddharth
committed
initial
0 parents  commit 8e09e0c

17 files changed

+418
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
venv/*
2+
*.pyc

Dockerfile

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
FROM python:3.7.3-slim-stretch
2+
3+
ENV PYTHONDONTWRITEBYTECODE 1
4+
ENV PYTHONUNBUFFERED 1
5+
6+
RUN mkdir /app
7+
8+
RUN apt update && apt upgrade -y && \
9+
apt install gcc default-libmysqlclient-dev -y && \
10+
pip install --upgrade pip
11+
WORKDIR /app
12+
13+
COPY . /app/
14+
RUN pip install -r requirements.txt
15+
16+
EXPOSE 8000
17+
18+
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

Procfile

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
web: python manage.py runserver 0.0.0.0:8000
2+
cmd: celery -A proj worker -l INFO

README.rst

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
==============================================================
2+
Example Django project using Celery
3+
==============================================================
4+
5+
* For sqlite testing, we can implement migration through the docker file via adding another command. `python manage.py makemigrations` and `python manage.py migrate`
6+
7+
Credits: Originally from https://github.com/celery/celery/tree/master/examples/django
8+
9+
Modified the app file just to add a hello-world end point (/api-check/) for validation.
10+
11+
Contents
12+
========
13+
14+
``proj/``
15+
---------
16+
17+
This is a project in itself, created using
18+
``django-admin.py startproject proj``, and then the settings module
19+
(``proj/settings.py``) was modified to add ``demoapp`` to
20+
``INSTALLED_APPS``
21+
22+
``proj/celery.py``
23+
----------
24+
25+
This module contains the Celery application instance for this project,
26+
we take configuration from Django settings and use ``autodiscover_tasks`` to
27+
find task modules inside all packages listed in ``INSTALLED_APPS``.
28+
29+
``demoapp/``
30+
------------
31+
32+
Example generic app. This is decoupled from the rest of the project by using
33+
the ``@shared_task`` decorator. This decorator returns a proxy that always
34+
points to the currently active Celery instance.
35+
36+
Installing requirements
37+
=======================
38+
39+
The settings file assumes that ``rabbitmq-server`` is running on ``localhost``
40+
using the default ports. More information here:
41+
42+
http://docs.celeryproject.org/en/latest/getting-started/brokers/rabbitmq.html
43+
44+
In addition, some Python requirements must also be satisfied:
45+
46+
.. code-block:: console
47+
48+
$ pip install -r requirements.txt
49+
50+
Starting the worker
51+
===================
52+
53+
.. code-block:: console
54+
55+
$ celery -A proj worker -l INFO
56+
57+
Running a task
58+
===================
59+
60+
.. code-block:: console
61+
62+
$ python ./manage.py shell
63+
>>> from demoapp.tasks import add, mul, xsum
64+
>>> res = add.delay(2,3)
65+
>>> res.get()
66+
5

demoapp/__init__.py

Whitespace-only changes.

demoapp/migrations/0001_initial.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Generated by Django 2.2.1 on 2019-05-24 21:37
2+
3+
from django.db import migrations, models
4+
5+
6+
class Migration(migrations.Migration):
7+
8+
initial = True
9+
10+
dependencies = [
11+
]
12+
13+
operations = [
14+
migrations.CreateModel(
15+
name='Widget',
16+
fields=[
17+
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18+
('name', models.CharField(max_length=140)),
19+
],
20+
),
21+
]

demoapp/migrations/__init__.py

Whitespace-only changes.

demoapp/models.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from django.db import models
2+
3+
4+
class Widget(models.Model):
5+
name = models.CharField(max_length=140)

demoapp/tasks.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Create your tasks here
2+
3+
from demoapp.models import Widget
4+
5+
from celery import shared_task
6+
7+
8+
@shared_task
9+
def add(x, y):
10+
return x + y
11+
12+
13+
@shared_task
14+
def mul(x, y):
15+
return x * y
16+
17+
18+
@shared_task
19+
def xsum(numbers):
20+
return sum(numbers)
21+
22+
23+
@shared_task
24+
def count_widgets():
25+
return Widget.objects.count()
26+
27+
28+
@shared_task
29+
def rename_widget(widget_id, name):
30+
w = Widget.objects.get(id=widget_id)
31+
w.name = name
32+
w.save()

demoapp/views.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Create your views here.
2+
from rest_framework.views import APIView
3+
from rest_framework.response import Response
4+
5+
class HomeAPIView(APIView):
6+
def get(self, request, format=None):
7+
return Response({"desc": "hello world"})

manage.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/usr/bin/env python
2+
3+
import os
4+
import sys
5+
6+
if __name__ == '__main__':
7+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
8+
9+
from django.core.management import execute_from_command_line
10+
11+
execute_from_command_line(sys.argv)

proj/__init__.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# This will make sure the app is always imported when
2+
# Django starts so that shared_task will use this app.
3+
from .celery import app as celery_app
4+
5+
__all__ = ('celery_app',)

proj/celery.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import os
2+
3+
from celery import Celery
4+
5+
# Set the default Django settings module for the 'celery' program.
6+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
7+
8+
app = Celery('proj')
9+
10+
# Using a string here means the worker doesn't have to serialize
11+
# the configuration object to child processes.
12+
# - namespace='CELERY' means all celery-related configuration keys
13+
# should have a `CELERY_` prefix.
14+
app.config_from_object('django.conf:settings', namespace='CELERY')
15+
16+
# Load task modules from all registered Django apps.
17+
app.autodiscover_tasks()
18+
19+
20+
@app.task(bind=True)
21+
def debug_task(self):
22+
print(f'Request: {self.request!r}')

proj/settings.py

+149
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import os
2+
3+
# ^^^ The above is required if you want to import from the celery
4+
# library. If you don't have this then `from celery.schedules import`
5+
# becomes `proj.celery.schedules` in Python 2.x since it allows
6+
# for relative imports by default.
7+
8+
# Celery settings
9+
10+
CELERY_BROKER_URL = 'amqp://guest:guest@localhost'
11+
12+
#: Only add pickle to this list if your broker is secured
13+
#: from unwanted access (see userguide/security.html)
14+
CELERY_ACCEPT_CONTENT = ['json']
15+
CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite'
16+
CELERY_TASK_SERIALIZER = 'json'
17+
18+
19+
"""
20+
Django settings for proj project.
21+
22+
Generated by 'django-admin startproject' using Django 2.2.1.
23+
24+
For more information on this file, see
25+
https://docs.djangoproject.com/en/2.2/topics/settings/
26+
27+
For the full list of settings and their values, see
28+
https://docs.djangoproject.com/en/2.2/ref/settings/
29+
"""
30+
31+
32+
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
33+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
34+
35+
36+
# Quick-start development settings - unsuitable for production
37+
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
38+
39+
# SECURITY WARNING: keep the secret key used in production secret!
40+
SECRET_KEY = 'l!t+dmzf97rt9s*yrsux1py_1@odvz1szr&6&m!f@-nxq6k%%p'
41+
42+
# SECURITY WARNING: don't run with debug turned on in production!
43+
DEBUG = True
44+
45+
ALLOWED_HOSTS = ['*']
46+
47+
48+
# Application definition
49+
50+
INSTALLED_APPS = [
51+
'django.contrib.admin',
52+
'django.contrib.auth',
53+
'django.contrib.contenttypes',
54+
'django.contrib.sessions',
55+
'django.contrib.messages',
56+
'django.contrib.staticfiles',
57+
'demoapp',
58+
]
59+
60+
MIDDLEWARE = [
61+
'django.middleware.security.SecurityMiddleware',
62+
'django.contrib.sessions.middleware.SessionMiddleware',
63+
'django.middleware.common.CommonMiddleware',
64+
'django.middleware.csrf.CsrfViewMiddleware',
65+
'django.contrib.auth.middleware.AuthenticationMiddleware',
66+
'django.contrib.messages.middleware.MessageMiddleware',
67+
'django.middleware.clickjacking.XFrameOptionsMiddleware',
68+
]
69+
70+
ROOT_URLCONF = 'proj.urls'
71+
72+
TEMPLATES = [
73+
{
74+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
75+
'DIRS': [],
76+
'APP_DIRS': True,
77+
'OPTIONS': {
78+
'context_processors': [
79+
'django.template.context_processors.debug',
80+
'django.template.context_processors.request',
81+
'django.contrib.auth.context_processors.auth',
82+
'django.contrib.messages.context_processors.messages',
83+
],
84+
},
85+
},
86+
]
87+
88+
WSGI_APPLICATION = 'proj.wsgi.application'
89+
90+
91+
# Database
92+
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
93+
94+
DATABASES = {
95+
'default': {
96+
'ENGINE': 'django.db.backends.sqlite3',
97+
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
98+
}
99+
}
100+
101+
# DATABASES = {
102+
# 'default': {
103+
# 'ENGINE': 'django.db.backends.mysql',
104+
# 'HOST': '172.17.0.2',
105+
# 'POST': '3306',
106+
# 'NAME': 'testdb',
107+
# 'USER': 'caesar',
108+
# 'PASSWORD': 'toor'
109+
# },
110+
# }
111+
112+
113+
# Password validation
114+
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
115+
116+
AUTH_PASSWORD_VALIDATORS = [
117+
{
118+
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
119+
},
120+
{
121+
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
122+
},
123+
{
124+
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
125+
},
126+
{
127+
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
128+
},
129+
]
130+
131+
132+
# Internationalization
133+
# https://docs.djangoproject.com/en/2.2/topics/i18n/
134+
135+
LANGUAGE_CODE = 'en-us'
136+
137+
TIME_ZONE = 'UTC'
138+
139+
USE_I18N = True
140+
141+
USE_L10N = True
142+
143+
USE_TZ = True
144+
145+
146+
# Static files (CSS, JavaScript, Images)
147+
# https://docs.djangoproject.com/en/2.2/howto/static-files/
148+
149+
STATIC_URL = '/static/'

proj/urls.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# from django.urls import handler404, handler500, include, url # noqa
2+
3+
# Uncomment the next two lines to enable the admin:
4+
# from django.contrib import admin
5+
# admin.autodiscover()
6+
7+
from django.urls import path
8+
from demoapp.views import HomeAPIView
9+
10+
urlpatterns = [
11+
# Examples:
12+
# url(r'^$', 'proj.views.home', name='home'),
13+
# url(r'^proj/', include('proj.foo.urls')),
14+
15+
# Uncomment the admin/doc line below to enable admin documentation:
16+
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
17+
18+
# Uncomment the next line to enable the admin:
19+
# url(r'^admin/', include(admin.site.urls)),
20+
path('api-check/', HomeAPIView.as_view())
21+
]

0 commit comments

Comments
 (0)