diff --git a/.gitignore b/.gitignore index 73ee260b..9dc5c298 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ .tox django_viewflow.egg-info db.sqlite3 +docs/_build/** tests/local_settings.py diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..2f831172 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +build_docs: + sphinx-build -b html docs/ docs/_build/ \ No newline at end of file diff --git a/README.rst b/README.rst index eea8f354..2014ce6f 100644 --- a/README.rst +++ b/README.rst @@ -7,14 +7,25 @@ Ad-hoc business process automation framework for Django django-viewflow provides simple, django friendly way to organize views, background jobs, user permission checking, in one clearly defined task flow. -django-viewflow does not introduce any restriction on views, urls or celery tasks, and should plays well -in any other django project. +Installation +============ + +django-viewflow requires Python 3.3 or grater and django 1.7:: + + pip install django-viewflow + +And add it into INSTALLED_APPS settings:: + + INSTALLED_APPS = ( + ... + viewflow, + ) Quick start =========== -Let's define basic Hello Process where one could start hello world request, and another approve it, -when request approved, it should be send. +Let's define basic Hello Process where one could start hello world request, another approve it, +and when request approved, it should be send in background. Start with process model definition:: @@ -84,6 +95,13 @@ Next, you can see how to define custom views `TODO` meet with and other concepts More examples available in `tests\\examples` directory + +License +====== +|The GNU General Public License v3.0| + +.. |The GNU General Public License v3.0| https://www.gnu.org/copyleft/gpl.html + Change log ========== diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 00000000..5daa087e --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# django-viewflow documentation build configuration file, created by +# sphinx-quickstart on Tue Apr 29 16:50:19 2014. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.todo', + 'sphinx.ext.coverage', + 'sphinx.ext.viewcode', +] + +# Add any paths that contain templates here, relative to this directory. +# templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'django-viewflow' +copyright = '2014, Mikhail Podgurskiy' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.1.0' +# The full version, including alpha/beta/rc tags. +release = '0.1.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'django-viewflowdoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ('index', 'django-viewflow.tex', 'django-viewflow Documentation', + 'Mikhail Podgurskiy', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'django-viewflow', 'django-viewflow Documentation', + ['Mikhail Podgurskiy'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'django-viewflow', 'django-viewflow Documentation', + 'Mikhail Podgurskiy', 'django-viewflow', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/docs/core_concepts.rst b/docs/core_concepts.rst new file mode 100644 index 00000000..1e70dc45 --- /dev/null +++ b/docs/core_concepts.rst @@ -0,0 +1,14 @@ +============= +Core concepts +============= + +Flow and Flow Tasks +=================== + + +Activation +========== + + +Core django +=========== diff --git a/docs/examples.rst b/docs/examples.rst new file mode 100644 index 00000000..dc17f59b --- /dev/null +++ b/docs/examples.rst @@ -0,0 +1,15 @@ +======== +Examples +======== + + +Hello, world +============ + +This example demostrate basic flow construction + + +Shipment +======== + +Standard BPMN example Shipment Process automated in hundred lines diff --git a/docs/flow_tasks.rst b/docs/flow_tasks.rst new file mode 100644 index 00000000..71592d78 --- /dev/null +++ b/docs/flow_tasks.rst @@ -0,0 +1,26 @@ +========== +Flow tasks +========== + + +Start +===== + + +View +==== + +Job +=== + +If +=== + +Switch +====== + +Split +===== + +Join +==== diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 00000000..93203dad --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,120 @@ +=============== +django-viewflow +=============== + +Ad-hoc business process automation framework for Django + +django-viewflow provides simple, django friendly way to organize views, background jobs, user permission checking, +in one clearly defined task flow. + + +Installation +============ + +django-viewflow requires Python 3.3 or grater and django 1.7:: + + pip install django-viewflow + +And add it into INSTALLED_APPS settings:: + + INSTALLED_APPS = ( + ... + viewflow, + ) + + +Quick Start +=========== + +Let's define basic Hello Process where one could start hello world request, another approve it, +and when request approved, it should be send in background. + +Start with process model definition:: + + from django.db import models + from viewflow.models import Process + + class HelloworldProcess(Process): + text = models.ChatField(max_lenght=150, blank=True, null=True) + approved = models.BooleanField(default=False) + + class Meta: + permissions = [ + ('can_start_request', 'Can start hello world request'), + ('can_approve_request', 'Can approve hello world request') + ] + +Define the actual task that would perform Hello on World, in task.py:: + + import os + + from celery import shared_task + from viewflow.flow import flow_job + + @shared_task(bind=True) + @flow_job() + def send_hello_world_request(self, activation): + with open(os.devnull, "w") as world: + world.write(activation.process.text) + + +To make this code works flow definition is simple, put it in `flows.py` inside your django application + +.. code-block:: python + + from viewflow import flow + from viewflow.base import this, Flow + from viewflow.views import ProcessView + + class HelloWorldFlow(Flow): + start = flow.Start(StartView, fields=["text"]) \ + .Permission('helloworld.can_start_request') \ + .Activate(this.hello_world) + + approve = flow.View(ProcessView, fields=["approve"]) \ + .Permission('helloworld.can_approve_request') + .Next(this.check_approve) + + check_approve = flow.If(cond=lambda p: p.approved) \ + .OnTrue(this.send) \ + .OnFalse(this.end) + + send = flow.Job(send_hello_world_request) \ + .Next(this.end) + + end = flow.End() + +`Flow` class contains all url required for task processing:: + + from django.conf.urls import patterns, url, include + from .flows import HelloWorldFlow + + urlpatterns = patterns('', + url(r'^helloworld/', include(HelloWorldFlow.instance.urls))) + + +That's all you need to setup this flow. + +Next, you can see how to define custom views `TODO` meet with and other concepts `TODO` of django-viewflow + +More examples available in `tests\\examples` directory + + + +Contents: +========= + +.. toctree:: + :maxdepth: 2 + + core_concepts + flow_tasks + examples + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/tox.ini b/tox.ini index 96fa94d5..cac61d75 100644 --- a/tox.ini +++ b/tox.ini @@ -10,4 +10,3 @@ deps = -r{toxinidir}/requirements.txt psycopg2 git+https://github.com/philipaxer/pygraphviz ipdb - diff --git a/viewflow/flow/end.py b/viewflow/flow/end.py index c10d8cdd..7e068a69 100644 --- a/viewflow/flow/end.py +++ b/viewflow/flow/end.py @@ -18,4 +18,3 @@ def __init__(self): def _outgoing(self): return iter([]) - diff --git a/viewflow/flow/gates.py b/viewflow/flow/gates.py index fe050710..fc35fa9d 100644 --- a/viewflow/flow/gates.py +++ b/viewflow/flow/gates.py @@ -23,6 +23,11 @@ def activate_next(self): class If(Gateway): """ Activates one of paths based on condition + + Example + check_decision = flow.If(lambda p: p.approved) \ + .OnTrue(this.approved) + .OnFalse(this.end) """ task_type = 'IF' activation_cls = IfActivation @@ -191,6 +196,12 @@ def activate(cls, flow_task, prev_activation, token): class Join(Gateway): """ Wait for one or all incoming links and activate next path + + Join should be connected to one split task only + + Example: + join_on_warehouse = self.Join() \ + .Next(this.next_task) """ task_type = 'JOIN' activation_cls = JoinActivation @@ -235,6 +246,11 @@ def activate_next(self): class Split(Gateway): """ Activate outgoing path in-parallel depends on per-path condition + + Example: + split_on_decision = flow.Split() \ + .Next(check_post, cond=lambda p: p,is_check_post_required) + .Next(this.perform_task_always) """ task_type = 'SPLIT' activation_cls = SplitActivation diff --git a/viewflow/flow/job.py b/viewflow/flow/job.py index 828080b2..26a47023 100644 --- a/viewflow/flow/job.py +++ b/viewflow/flow/job.py @@ -8,6 +8,21 @@ def flow_job(**lock_args): + """ + Decorator that prepares celery task for execution + + Makes celry job function with following signature: + :: (flow_task-strref, process_pk, task_pk, **kwargs) + + Expects actual celery job function have following signature + :: (activation, **kwargs) + If celery task class implements activation interface, job function + called without activation instance + :: (activation, **kwargs) + + Process instannce are locked only before and after function execution. + Plese avoid any process state modification during the celery job + """ class flow_task_decorator(object): def __init__(self, func, activation=None): self.func = func @@ -69,6 +84,10 @@ def __get__(self, instance, instancetype): class Job(Task): """ Task that runs in background + + Example: + job = flow.Job(task.job) \ + .Next(this.end) """ task_type = 'JOB' activation_cls = JobActivation diff --git a/viewflow/flow/start.py b/viewflow/flow/start.py index ae2dc430..4cee5081 100644 --- a/viewflow/flow/start.py +++ b/viewflow/flow/start.py @@ -91,7 +91,7 @@ def prepare(self, data=None): class StartViewMixin(object): """ - Mixin for start views, not implementing activation + Mixin for start views, that not implements activation interface """ def get_context_data(self, **kwargs): context = super(StartViewMixin, self).get_context_data(**kwargs) @@ -121,6 +121,9 @@ def dispatch(self, request, activation, **kwargs): class StartView(StartViewActivation, UpdateView): + """ + Generic start view + """ fields = [] @property @@ -159,6 +162,11 @@ def dispatch(self, request, *args, **kwargs): class Start(Event): """ Start process event + + Example: + start = flow.Start(StartView, fields=["some_process_field"]) \ + .Available(lambda user: user.is_super_user) \ + .Activate(this.first_start) """ task_type = 'START' activation_cls = StartViewActivation diff --git a/viewflow/flow/view.py b/viewflow/flow/view.py index c707c6c2..7df328ef 100644 --- a/viewflow/flow/view.py +++ b/viewflow/flow/view.py @@ -99,7 +99,7 @@ def prepare(self, data=None): class TaskViewMixin(object): """ - Mixin for task views, not implementing activation + Mixin for task views, that not implements activation interface """ def get_context_data(self, **kwargs): context = super(TaskViewMixin, self).get_context_data(**kwargs) @@ -175,6 +175,14 @@ def dispatch(self, request, *args, **kwargs): class View(Task): + """ + View task + + Example: + task = flow.View(some_view) \ + .Permission('my_app.can_do_task') \ + .Next(this.next_task) + """ task_type = 'HUMAN' activation_cls = TaskViewActivation @@ -216,7 +224,7 @@ def Assign(self, owner=None, **owner_kwargs): accepts user lookup kwargs or callable :: Process -> User .Assign(username='employee') - .Assign(lambda task: task.process.created_by) + .Assign(lambda process: process.created_by) """ if owner: self._owner = owner @@ -230,7 +238,7 @@ def Permission(self, permission, assign_view=None): aceps permissions name of callable :: Process -> permission_name .Permission('my_app.can_approve') - .Permission(lambda task: 'my_app.department_manager_{}'.format(task.process.depratment.pk)) + .Permission(lambda process: 'my_app.department_manager_{}'.format(process.depratment.pk)) """ self._owner_permission = permission self._assign_view = assign_view