Skip to content

Commit

Permalink
Fresh celery sample
Browse files Browse the repository at this point in the history
  • Loading branch information
kmmbvnr committed Feb 10, 2017
1 parent a0c2256 commit 00c0a34
Show file tree
Hide file tree
Showing 17 changed files with 403 additions and 3 deletions.
5 changes: 5 additions & 0 deletions celery/demo/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from __future__ import absolute_import

from .celery import app as celery_app

__all__ = ['celery_app']
17 changes: 17 additions & 0 deletions celery/demo/celery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings')

app = Celery('demo')

# Using a string here means the worker don'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()
Empty file.
5 changes: 5 additions & 0 deletions celery/demo/hellocelery/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class HellowoldConfig(AppConfig):
name = 'hellowold'
44 changes: 44 additions & 0 deletions celery/demo/hellocelery/flows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from viewflow import flow, frontend
from viewflow.base import this, Flow
from viewflow.contrib import celery
from viewflow.flow.views import CreateProcessView, UpdateProcessView

from .models import HelloWorldProcess
from .tasks import send_hello_world_request


@frontend.register
class HelloWorldFlow(Flow):
process_class = HelloWorldProcess

start = (
flow.Start(
CreateProcessView,
fields=["text"]
).Permission(
auto_create=True
).Next(this.approve)
)

approve = (
flow.View(
UpdateProcessView,
fields=["approved"]
).Permission(
auto_create=True
).Next(this.check_approve)
)

check_approve = (
flow.If(lambda activation: activation.process.approved)
.Then(this.send)
.Else(this.end)
)

send = (
celery.Job(
send_hello_world_request
).Next(this.end)
)

end = flow.End()
30 changes: 30 additions & 0 deletions celery/demo/hellocelery/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-10 06:15
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
('viewflow', '0005_rename_flowcls'),
]

operations = [
migrations.CreateModel(
name='HelloWorldProcess',
fields=[
('process_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='viewflow.Process')),
('text', models.CharField(max_length=150)),
('approved', models.BooleanField(default=False)),
],
options={
'abstract': False,
},
bases=('viewflow.process',),
),
]
Empty file.
7 changes: 7 additions & 0 deletions celery/demo/hellocelery/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.db import models
from viewflow.models import Process


class HelloWorldProcess(Process):
text = models.CharField(max_length=150)
approved = models.BooleanField(default=False)
13 changes: 13 additions & 0 deletions celery/demo/hellocelery/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from celery import shared_task
from celery.utils.log import get_task_logger

from viewflow.flow import flow_job


logger = get_task_logger(__name__)


@shared_task
@flow_job
def send_hello_world_request(activation):
logger.info(activation.process.text)
140 changes: 140 additions & 0 deletions celery/demo/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""
Django settings for demo project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+20@e^&9z9ef^i^!fti+$v7d!uwetg07^1b$xels75h!6uo&^p'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'material',
'material.frontend',
'viewflow',
'viewflow.frontend',
'demo.hellocelery',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

import django
if django.VERSION < (1, 10):
MIDDLEWARE_CLASSES = MIDDLEWARE

ROOT_URLCONF = 'demo.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'demo.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'


# Celery
# http://docs.celeryproject.org/en/latest/
CELERY_ACCEPT_CONTENT = ['json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'

# Test only
CELERY_TASK_ALWAYS_EAGER = True
CELERY_TASK_EAGER_PROPAGATES = True

53 changes: 53 additions & 0 deletions celery/demo/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from django.contrib.auth.models import User
from django.test import TestCase
from viewflow.models import Process


class Test(TestCase):
def setUp(self):
User.objects.create_superuser('admin', 'admin@example.com', 'password')
self.client.login(username='admin', password='password')

def testApproved(self):
self.client.post(
'/workflow/hellocelery/start/',
{'text': 'Hello, celery',
'_viewflow_activation-started': '2000-01-01'}
)

self.client.post(
'/workflow/hellocelery/1/approve/2/assign/'
)

self.client.post(
'/workflow/hellocelery/1/approve/2/',
{'approved': True,
'_viewflow_activation-started': '2000-01-01'}
)

process = Process.objects.get()

self.assertEquals('DONE', process.status)
self.assertEquals(5, process.task_set.count())

def testNotApproved(self):
self.client.post(
'/workflow/hellocelery/start/',
{'text': 'Hello, celery',
'_viewflow_activation-started': '2000-01-01'}
)

self.client.post(
'/workflow/hellocelery/1/approve/2/assign/'
)

self.client.post(
'/workflow/hellocelery/1/approve/2/',
{'approved': False,
'_viewflow_activation-started': '2000-01-01'}
)

process = Process.objects.get()

self.assertEquals('DONE', process.status)
self.assertEquals(4, process.task_set.count())
23 changes: 23 additions & 0 deletions celery/demo/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""demo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.views import generic
from material.frontend import urls as frontend_urls

urlpatterns = [
url(r'^$', generic.RedirectView.as_view(url='/workflow/', permanent=False)),
url(r'', include(frontend_urls)),
]
16 changes: 16 additions & 0 deletions celery/demo/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for demo project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings")

application = get_wsgi_application()
22 changes: 22 additions & 0 deletions celery/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
5 changes: 5 additions & 0 deletions celery/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
django==1.10.5
celery==4.0.2
django-material==0.12.3
viewflow-pro=0.12.0

Loading

0 comments on commit 00c0a34

Please sign in to comment.