-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 30c19df
Showing
7 changed files
with
491 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,139 @@ | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
|
||
# C extensions | ||
*.so | ||
|
||
# Distribution / packaging | ||
.Python | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
wheels/ | ||
share/python-wheels/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
MANIFEST | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.nox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*.cover | ||
*.py,cover | ||
.hypothesis/ | ||
.pytest_cache/ | ||
cover/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
db.sqlite3 | ||
db.sqlite3-journal | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
.pybuilder/ | ||
target/ | ||
|
||
# Jupyter Notebook | ||
.ipynb_checkpoints | ||
|
||
# IPython | ||
profile_default/ | ||
ipython_config.py | ||
|
||
# pyenv | ||
# For a library or package, you might want to ignore these files since the code is | ||
# intended to run in multiple environments; otherwise, check them in: | ||
.python-version | ||
|
||
# pipenv | ||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. | ||
# However, in case of collaboration, if having platform-specific dependencies or dependencies | ||
# having no cross-platform support, pipenv may install dependencies that don't work, or not | ||
# install all needed dependencies. | ||
#Pipfile.lock | ||
|
||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow | ||
__pypackages__/ | ||
|
||
# Celery stuff | ||
celerybeat-schedule | ||
celerybeat.pid | ||
|
||
# SageMath parsed files | ||
*.sage.py | ||
|
||
# Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
.idea/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
.spyproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# mkdocs documentation | ||
/site | ||
|
||
# mypy | ||
.mypy_cache/ | ||
.dmypy.json | ||
dmypy.json | ||
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
# pytype static type analyzer | ||
.pytype/ | ||
|
||
# Cython debug symbols | ||
cython_debug/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2021 Neeraj Kumar | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,191 @@ | ||
=============== | ||
Django FSM with Django Rest Framework. | ||
=============== | ||
|
||
Overview | ||
======== | ||
drf_fsm library provides an endpoint for defined each transition in models using Django FSM with Django Rest Framework library. | ||
|
||
|
||
Features | ||
======== | ||
This library provides endpoint for each transition of FSM and customize like: | ||
|
||
1. Easy to define the number of FSM fields that's the endpoint you want to create automatically. default : No field. | ||
2. Easy to define how many transitions endpoint you want to create for particular field: default: all transition of fields. | ||
3. Easy to define serializer for each transition and field name wise: default: serializer_class of ViewSet. | ||
4. Easy to handle response for each endpoint of transition and field, default: serializer.data . | ||
|
||
Installation | ||
============ | ||
|
||
- Install drf_fsm using pip:: | ||
|
||
pip install drf_fsm | ||
|
||
- Import Mixin from drf_fsm and Use in ViewSet views of DRF:: | ||
|
||
from drf_fsm.mixins import FsmViewSetMixin | ||
|
||
|
||
Uses with example | ||
================ | ||
|
||
Lets Suppose a Post model that uses Django FSM | ||
|
||
models.py:: | ||
|
||
from django.contrib.auth import get_user_model | ||
from django.db import models | ||
from django_fsm import transition, FSMField | ||
|
||
User = get_user_model() | ||
|
||
|
||
class PostStatusChoices(models.TextChoices): | ||
Draft = 'draft', 'Draft' | ||
Pending = 'pending', 'Pending' | ||
Publish = 'publish', 'Publish' | ||
Future = 'future', 'Future' | ||
Trash = 'trash', 'Trash' | ||
|
||
|
||
class Post(models.Model): | ||
title = models.CharField(max_length=200, unique=True) | ||
slug = models.SlugField(max_length=200, unique=True) | ||
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') | ||
updated_on = models.DateTimeField(auto_now=True) | ||
content = models.TextField() | ||
created_on = models.DateTimeField(auto_now_add=True) | ||
status = FSMField('Status', max_length=20, default=PostStatusChoices.Draft, | ||
choices=PostStatusChoices.choices, protected=True) | ||
|
||
@transition(field=status, source='*', target=PostStatusChoices.Draft) | ||
def draft(self): | ||
pass | ||
|
||
@transition(field=status, source=PostStatusChoices.Draft, target=PostStatusChoices.Pending) | ||
def pending(self): | ||
pass | ||
|
||
@transition(field=status, source=PostStatusChoices.Pending, target=PostStatusChoices.Publish) | ||
def publish(self): | ||
pass | ||
|
||
@transition(field=status, source=PostStatusChoices.Pending, target=PostStatusChoices.Future) | ||
def future(self): | ||
pass | ||
|
||
@transition(field=status, source='*', target=PostStatusChoices.Trash) | ||
def trash(self): | ||
pass | ||
|
||
|
||
|
||
|
||
We define model with 5 choices above and added 5 transition for each status in model. | ||
|
||
Now create ViewSet for Post model | ||
|
||
views.py:: | ||
|
||
from rest_framework.viewsets import ModelViewSet | ||
from drf_fsm.mixins import FsmViewSetMixin | ||
from .models import Post | ||
from .serializers import PostSerializer | ||
|
||
|
||
class PostViewSet(FsmViewSetMixin, ModelViewSet): | ||
queryset = Post.objects.all() | ||
serializer_class = PostSerializer | ||
fsm_fields = ['status'] | ||
|
||
|
||
Here we define "status" as a FSM field, we can define multiple in list if we have multiple in single model | ||
|
||
Connect this views to DRF router | ||
urls.py:: | ||
|
||
from rest_framework.routers import DefaultRouter | ||
from .views import PostViewSet | ||
|
||
router = DefaultRouter() | ||
|
||
router.register('post', PostViewSet, basename="post_view_set") | ||
|
||
urlpatterns = router.urls | ||
|
||
|
||
Finished. Cheers ✌️ | ||
------------------ | ||
|
||
Now checking Output in Swagger | ||
|
||
.. image:: output.png | ||
:width: 100% | ||
|
||
|
||
😎 :), | ||
==== | ||
|
||
Let's move to customizations: | ||
|
||
Customizations | ||
============ | ||
|
||
1. Define number of fields of FSM in view like:: | ||
|
||
fsm_fields = ['status', 'priority'] | ||
|
||
2. Define particular transitions for include, left will ignore for endpoints. | ||
suppose field name is "status" and have 5 transition according above example so we can | ||
handle which transition should include and other ignore. | ||
|
||
So write @classmethod in viewset for override this feature:: | ||
|
||
@classmethod | ||
def status_transitions(cls): # Here status in field name so it's dynamic based on FSM field name. | ||
return ['trash', 'publish'] | ||
|
||
Here "trash" and "publish" transition endpoint will available for API, other will ignore from endpoints | ||
|
||
3. Define serializer class for each transition or field name wise:: | ||
|
||
publish_status_serializer_class = PublishStatusPostSerializer # {transition}_{field_name}_serializer_class | ||
|
||
or | ||
|
||
status_serializer_class = StatusPostSerializer # {field_name}_serializer_class | ||
|
||
or, default | ||
|
||
serializer_class = PostSerializer # Default serializer class for each | ||
|
||
Serializer class uses dynamic name for each transition if define otherwise default will use. | ||
|
||
4. Define Response of each transition:: | ||
|
||
def publish_status_response(self, serializer): # {transition}_{field_name}_response | ||
return {"message": "Post status updated published"} | ||
|
||
or | ||
|
||
def status_response(self, serializer): # {field_name}_response, but it'll show for all transition of status field | ||
return {"message": "Post status updated"} | ||
|
||
or, default | ||
|
||
serializer.data | ||
|
||
|
||
|
||
|
||
If you feel this library is useful for your work just buy some coffee for me so I'll try improved this and will work on new libraries. | ||
|
||
<a href="https://www.buymeacoffee.com/sainipray" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a> | ||
|
||
License | ||
======= | ||
|
||
drf_fsm is an Open Source project licensed under the terms of the `MIT license <https://github.com/sainipray/drf-fsm/blob/main/LICENSE>`_ | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
__name__ = 'drf_fsm' | ||
__author__ = 'Neeraj Kumar' | ||
__version__ = '1.0.0' | ||
__author_email__ = '[email protected]' | ||
__description__ = 'Create Django FSM transitions as a endpoint with Django REST Framework' |
Oops, something went wrong.