=========
drf-turbo
=========
.. image:: https://img.shields.io/pypi/v/drf-turbo.svg
:target: https://pypi.python.org/pypi/drf-turbo
:alt: Version
.. image:: https://readthedocs.org/projects/drf-turbo/badge/?version=latest
:target: https://drf-turbo.readthedocs.io/en/latest/?version=latest
:alt: Documentation Status
.. image:: https://static.pepy.tech/personalized-badge/drf-turbo?period=total&units=international_system&left_color=black&right_color=green&left_text=Downloads
:target: https://pepy.tech/project/drf-turbo/
:alt: Downloads
Overview
------------
drf-turbo is a drop-in serializer for Django REST Framework (DRF). drf-turbo serializers run around 7.75 times faster
than what what you get from DRF's packaged serializer.
Requirements
------------
* Django
* Django REST Framework
* pytz
* forbiddenfruit
* pyyaml(OpenAPI)
* uritemplate(OpenAPI)
* djangorestframework-simplejwt(OpenAPI)
Installation
------------
.. code-block:: console
$ pip install drf-turbo
To install Cython on MacOS `via Brew <https://formulae.brew.sh/formula/cython>`_:
.. code-block:: console
$ brew install cython
Performance
-----------
`drf-turbo` serialization, deserialization and validation performance averages 86% faster than DRF's standard serializer.
For more details, visit the `benchmarks section <https://drf-turbo.readthedocs.io/en/latest/performance.html>`_ of the docs.
Documentation & Support
-----------------------
Documentation for the project is available at https://drf-turbo.readthedocs.io.
For questions and support, use github issues
Examples
========
Declaring Serializers
---------------------
.. code-block:: python
from datetime import datetime
from django.utils.timezone import now
import drf_turbo as dt
class User:
def __init__(self, username, email,created=None):
self.username = username
self.email = email
self.created = created or datetime.now()
user = User(username='test' , email='test@example.com')
class UserSerializer(dt.Serializer):
username = dt.StrField(max_length=50)
email = dt.EmailField()
created = dt.DateTimeField()
Serializing objects
-------------------
.. code-block:: python
serializer = UserSerializer(user)
serializer.data
# {'username': 'test', 'email': 'test@example.com', 'created': '2021-11-04T22:49:01.981127Z'}
Deserializing objects
---------------------
.. code-block:: python
data = {'username':'new_test','email':'test2@example.com','created':now()}
serializer = UserSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# {'username': 'new_test', 'email': 'test2@example.com', 'created': datetime.datetime(2021, 11, 12, 6, 10, 44, 85118)}}
Validation
----------
.. code-block:: python
serializer = UserSerializer(data={'email': 'test'})
serializer.is_valid()
# False
serializer.errors
# {'username': ['This field is required.'], 'email': ['Enter a valid email address.'],'created': ['This field is required.']}
Field-level validation
----------------------
.. code-block:: python
import drf_turbo as dt
class UserSerializer(dt.Serializer):
username = dt.StrField(max_length=50)
def validate_username(self, value):
if 'test' not in value.lower():
raise dt.ValidationError("test must be in username")
return value
Object-level validation
-----------------------
.. code-block:: python
import drf_turbo as dt
class CampaignSerializer(dt.Serializer):
start_date = dt.DateTimeField()
end_date = dt.DateTimeField()
def validate(self, data):
if data['start_date'] > data['end_date']:
raise dt.ValidationError("start_date must occur before end_date")
return data
Nested Serializers
------------------
.. code-block:: python
from datetime import datetime
from django.utils.timezone import now
import drf_turbo as dt
class User:
def __init__(self, username, email,created=None):
self.username = username
self.email = email
self.created = created or datetime.now()
user = User(username='test' , email='test@example.com')
class UserSerializer(dt.Serializer):
username = dt.StrField(max_length=50)
email = dt.EmailField()
created = dt.DateTimeField()
class Profile :
def __init__(self, age=25):
self.age = age
self.user = user
profile = Profile()
class ProfileSerializer(dt.Serializer):
age = dt.IntField()
user = UserSerializer()
serializer = ProfileSerializer(profile)
serializer.data
# {'age' : 25 , 'user' : {'username': 'test', 'email': 'test@example.com', 'created': '2021-11-04T22:49:01.981127Z'}}
Filtering Output
----------------
drf-turbo provides option to enclude or exclude fields from serializer using ``only`` or ``exclude`` keywords.
.. code-block:: python
serializer = UserSerializer(user,only=('id','username'))
or
serializer = ProfileSerializer(profile,exclude=('id','user__email'))
or
http://127.0.0.1:8000/user/?only=id,username
Required Fields
---------------
Make a field required by passing required=True. An error will be raised if the the value is missing from data during Deserializing.
For example:
.. code-block:: python
class UserSerializer(dt.Serializer):
username = dt.StrField(required=True,error_messages={"required":"no username"})
Specifying Defaults
-------------------
It will be used for the field if no input value is supplied.
For example:
.. code-block:: python
from datetime import datetime
class UserSerializer(dt.Serializer):
birthdate = dt.DateTimeField(default=datetime(2021, 11, 05))
ModelSerializer
---------------
Mapping serializer to Django model definitions.
Features :
* It will automatically generate a set of fields for you, based on the model.
* It will automatically generate validators for the serializer.
* It includes simple default implementations of .create() and .update().
.. code-block:: python
class UserSerializer(dt.ModelSerializer):
class Meta :
model = User
fields = ('id','username','email')
You can also set the fields attribute to the special value ``__all__`` to indicate that all fields in the model should be used.
For example:
.. code-block:: python
class UserSerializer(dt.ModelSerializer):
class Meta :
model = User
fields = '__all__'
You can set the exclude attribute to a list of fields to be excluded from the serializer.
For example:
.. code-block:: python
class UserSerializer(dt.ModelSerializer):
class Meta :
model = User
exclude = ('email',)
Read&Write only fields
----------------------
.. code-block:: python
class UserSerializer(dt.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password','password_confirmation')
read_only_fields = ('username')
write_only_fields = ('password','password_confirmation')
OpenApi(Swagger)
----------------
Add drf-turbo to installed apps in ``settings.py``
.. code:: python
INSTALLED_APPS = [
# ALL YOUR APPS
'drf_turbo',
]
and then register our openapi AutoSchema with DRF.
.. code:: python
REST_FRAMEWORK = {
# YOUR SETTINGS
'DEFAULT_SCHEMA_CLASS': 'drf_turbo.openapi.AutoSchema',
}
and finally add these lines in ``urls.py``
.. code:: python
from django.views.generic import TemplateView
from rest_framework.schemas import get_schema_view as schema_view
from drf_turbo.openapi import SchemaGenerator
urlpatterns = [
# YOUR PATTERNS
path('openapi', schema_view(
title="Your Project",
description="API for all things …",
version="1.0.0",
generator_class=SchemaGenerator,
public=True,
), name='openapi-schema'),
path('docs/', TemplateView.as_view(
template_name='docs.html',
extra_context={'schema_url':'openapi-schema'}
), name='swagger-ui'),
]
Now go to http://127.0.0.1:8000/docs
Credits
-------
This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.
.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
License
------------
* Free software: MIT license
=======
History
=======
0.1.0 (2021-11-10)
------------------
* First release on PyPI.
0.1.2 (2021-11-11)
------------------
* performance improvments
0.1.3 (2021-11-12)
------------------
* fix override error messages
0.1.5 (2021-11-21)
------------------
* fix get_attribute on related field issue
0.1.6 (2022-05-29)
------------------
* clean project
* drop support for renderers,parsers, and responses
* remove deprecated methods
0.1.7 (2023-08-19)
------------------
* pin requirements
* use c extensions
0.1.8 (2023-10-11)
------------------
* add support for django 4.0
0.1.9 (2023-10-11)
------------------
* add support for python 3.10
Raw data
{
"_id": null,
"home_page": "https://github.com/Mng-dev-ai/drf-turbo",
"name": "drf-turbo",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.8, <3.11",
"maintainer_email": "",
"keywords": "drf_turbo",
"author": "Michael Gendy",
"author_email": "nagymichel13@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/21/57/957549fdd3d58babf6ce9d4f6c035d7ce15af38015fd52549cf5dfaf5626/drf-turbo-0.1.9.tar.gz",
"platform": null,
"description": "=========\ndrf-turbo\n=========\n\n\n.. image:: https://img.shields.io/pypi/v/drf-turbo.svg\n :target: https://pypi.python.org/pypi/drf-turbo\n :alt: Version\n\n.. image:: https://readthedocs.org/projects/drf-turbo/badge/?version=latest\n :target: https://drf-turbo.readthedocs.io/en/latest/?version=latest\n :alt: Documentation Status\n\n.. image:: https://static.pepy.tech/personalized-badge/drf-turbo?period=total&units=international_system&left_color=black&right_color=green&left_text=Downloads\n :target: https://pepy.tech/project/drf-turbo/\n :alt: Downloads\n\n\nOverview\n------------\ndrf-turbo is a drop-in serializer for Django REST Framework (DRF). drf-turbo serializers run around 7.75 times faster\nthan what what you get from DRF's packaged serializer.\n\n\nRequirements\n------------\n\n* Django\n\n* Django REST Framework\n\n* pytz\n\n* forbiddenfruit\n\n* pyyaml(OpenAPI)\n\n* uritemplate(OpenAPI)\n\n* djangorestframework-simplejwt(OpenAPI)\n\n\nInstallation\n------------\n\n.. code-block:: console\n\n $ pip install drf-turbo\n\nTo install Cython on MacOS `via Brew <https://formulae.brew.sh/formula/cython>`_:\n\n.. code-block:: console\n\n $ brew install cython\n\nPerformance\n-----------\n`drf-turbo` serialization, deserialization and validation performance averages 86% faster than DRF's standard serializer.\n\nFor more details, visit the `benchmarks section <https://drf-turbo.readthedocs.io/en/latest/performance.html>`_ of the docs.\n\nDocumentation & Support\n-----------------------\nDocumentation for the project is available at https://drf-turbo.readthedocs.io.\n\nFor questions and support, use github issues\n\nExamples\n========\n\nDeclaring Serializers\n---------------------\n.. code-block:: python\n\n from datetime import datetime\n from django.utils.timezone import now\n import drf_turbo as dt\n\n class User:\n def __init__(self, username, email,created=None):\n self.username = username\n self.email = email\n self.created = created or datetime.now()\n\n user = User(username='test' , email='test@example.com')\n\n\n\n class UserSerializer(dt.Serializer):\n username = dt.StrField(max_length=50)\n email = dt.EmailField()\n created = dt.DateTimeField()\n\n\nSerializing objects\n-------------------\n\n.. code-block:: python\n\n\n serializer = UserSerializer(user)\n serializer.data\n\n # {'username': 'test', 'email': 'test@example.com', 'created': '2021-11-04T22:49:01.981127Z'}\n\n\nDeserializing objects\n---------------------\n\n.. code-block:: python\n\n data = {'username':'new_test','email':'test2@example.com','created':now()}\n serializer = UserSerializer(data=data)\n serializer.is_valid()\n # True\n serializer.validated_data\n # {'username': 'new_test', 'email': 'test2@example.com', 'created': datetime.datetime(2021, 11, 12, 6, 10, 44, 85118)}}\n\nValidation\n----------\n\n.. code-block:: python\n\n serializer = UserSerializer(data={'email': 'test'})\n serializer.is_valid()\n # False\n serializer.errors\n # {'username': ['This field is required.'], 'email': ['Enter a valid email address.'],'created': ['This field is required.']}\n\n\nField-level validation\n----------------------\n\n.. code-block:: python\n\n import drf_turbo as dt\n\n class UserSerializer(dt.Serializer):\n username = dt.StrField(max_length=50)\n\n def validate_username(self, value):\n if 'test' not in value.lower():\n raise dt.ValidationError(\"test must be in username\")\n return value\n\nObject-level validation\n-----------------------\n\n.. code-block:: python\n\n import drf_turbo as dt\n\n class CampaignSerializer(dt.Serializer):\n start_date = dt.DateTimeField()\n end_date = dt.DateTimeField()\n\n def validate(self, data):\n if data['start_date'] > data['end_date']:\n raise dt.ValidationError(\"start_date must occur before end_date\")\n return data\n\nNested Serializers\n------------------\n.. code-block:: python\n\n from datetime import datetime\n from django.utils.timezone import now\n import drf_turbo as dt\n\n class User:\n def __init__(self, username, email,created=None):\n self.username = username\n self.email = email\n self.created = created or datetime.now()\n\n user = User(username='test' , email='test@example.com')\n\n class UserSerializer(dt.Serializer):\n username = dt.StrField(max_length=50)\n email = dt.EmailField()\n created = dt.DateTimeField()\n\n class Profile :\n def __init__(self, age=25):\n self.age = age\n self.user = user\n\n profile = Profile()\n\n\n class ProfileSerializer(dt.Serializer):\n age = dt.IntField()\n user = UserSerializer()\n\n\n serializer = ProfileSerializer(profile)\n serializer.data\n\n # {'age' : 25 , 'user' : {'username': 'test', 'email': 'test@example.com', 'created': '2021-11-04T22:49:01.981127Z'}}\n\n\nFiltering Output\n----------------\n\ndrf-turbo provides option to enclude or exclude fields from serializer using ``only`` or ``exclude`` keywords.\n\n.. code-block:: python\n\n serializer = UserSerializer(user,only=('id','username'))\n\n or\n\n serializer = ProfileSerializer(profile,exclude=('id','user__email'))\n\n or\n\n http://127.0.0.1:8000/user/?only=id,username\n\n\nRequired Fields\n---------------\n\nMake a field required by passing required=True. An error will be raised if the the value is missing from data during Deserializing.\n\nFor example:\n\n.. code-block:: python\n\n class UserSerializer(dt.Serializer):\n\n username = dt.StrField(required=True,error_messages={\"required\":\"no username\"})\n\n\n\nSpecifying Defaults\n-------------------\n\nIt will be used for the field if no input value is supplied.\n\n\nFor example:\n\n.. code-block:: python\n\n from datetime import datetime\n\n class UserSerializer(dt.Serializer):\n\n birthdate = dt.DateTimeField(default=datetime(2021, 11, 05))\n\n\n\n\nModelSerializer\n---------------\n\nMapping serializer to Django model definitions.\n\nFeatures :\n\n * It will automatically generate a set of fields for you, based on the model.\n * It will automatically generate validators for the serializer.\n * It includes simple default implementations of .create() and .update().\n\n.. code-block:: python\n\n class UserSerializer(dt.ModelSerializer):\n\n class Meta :\n model = User\n fields = ('id','username','email')\n\nYou can also set the fields attribute to the special value ``__all__`` to indicate that all fields in the model should be used.\n\nFor example:\n\n.. code-block:: python\n\n class UserSerializer(dt.ModelSerializer):\n\n class Meta :\n model = User\n fields = '__all__'\n\nYou can set the exclude attribute to a list of fields to be excluded from the serializer.\n\nFor example:\n\n.. code-block:: python\n\n class UserSerializer(dt.ModelSerializer):\n\n class Meta :\n model = User\n exclude = ('email',)\n\n\nRead&Write only fields\n----------------------\n\n.. code-block:: python\n\n class UserSerializer(dt.ModelSerializer):\n class Meta:\n model = User\n fields = ('id', 'username', 'password','password_confirmation')\n read_only_fields = ('username')\n write_only_fields = ('password','password_confirmation')\n\n\nOpenApi(Swagger)\n----------------\n\nAdd drf-turbo to installed apps in ``settings.py``\n\n.. code:: python\n\n INSTALLED_APPS = [\n # ALL YOUR APPS\n 'drf_turbo',\n ]\n\n\nand then register our openapi AutoSchema with DRF.\n\n.. code:: python\n\n REST_FRAMEWORK = {\n # YOUR SETTINGS\n 'DEFAULT_SCHEMA_CLASS': 'drf_turbo.openapi.AutoSchema',\n }\n\n\nand finally add these lines in ``urls.py``\n\n.. code:: python\n\n from django.views.generic import TemplateView\n from rest_framework.schemas import get_schema_view as schema_view\n from drf_turbo.openapi import SchemaGenerator\n\n urlpatterns = [\n # YOUR PATTERNS\n \tpath('openapi', schema_view(\n title=\"Your Project\",\n description=\"API for all things \u2026\",\n version=\"1.0.0\",\n generator_class=SchemaGenerator,\n public=True,\n ), name='openapi-schema'),\n path('docs/', TemplateView.as_view(\n template_name='docs.html',\n extra_context={'schema_url':'openapi-schema'}\n ), name='swagger-ui'),\n ]\n\nNow go to http://127.0.0.1:8000/docs\n\nCredits\n-------\n\nThis package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.\n\n.. _Cookiecutter: https://github.com/audreyr/cookiecutter\n.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage\n\nLicense\n------------\n* Free software: MIT license\n\n\n=======\nHistory\n=======\n\n0.1.0 (2021-11-10)\n------------------\n\n* First release on PyPI.\n\n\n0.1.2 (2021-11-11)\n------------------\n\n* performance improvments\n\n\n0.1.3 (2021-11-12)\n------------------\n\n* fix override error messages\n\n\n0.1.5 (2021-11-21)\n------------------\n\n* fix get_attribute on related field issue\n\n0.1.6 (2022-05-29)\n------------------\n* clean project\n* drop support for renderers,parsers, and responses\n* remove deprecated methods\n\n0.1.7 (2023-08-19)\n------------------\n* pin requirements\n* use c extensions\n\n0.1.8 (2023-10-11)\n------------------\n* add support for django 4.0\n\n0.1.9 (2023-10-11)\n------------------\n* add support for python 3.10\n",
"bugtrack_url": null,
"license": "MIT license",
"summary": "An alternative serializer implementation for REST framework written in cython built for speed.",
"version": "0.1.9",
"project_urls": {
"Homepage": "https://github.com/Mng-dev-ai/drf-turbo"
},
"split_keywords": [
"drf_turbo"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "2157957549fdd3d58babf6ce9d4f6c035d7ce15af38015fd52549cf5dfaf5626",
"md5": "26bf69b0b13fd190d61529dd881f7c42",
"sha256": "6155879be62064894e744c3ba614a7fd65ef78a12a357595ffaa9ce952422251"
},
"downloads": -1,
"filename": "drf-turbo-0.1.9.tar.gz",
"has_sig": false,
"md5_digest": "26bf69b0b13fd190d61529dd881f7c42",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8, <3.11",
"size": 565897,
"upload_time": "2023-10-11T01:50:48",
"upload_time_iso_8601": "2023-10-11T01:50:48.797820Z",
"url": "https://files.pythonhosted.org/packages/21/57/957549fdd3d58babf6ce9d4f6c035d7ce15af38015fd52549cf5dfaf5626/drf-turbo-0.1.9.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-10-11 01:50:48",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "Mng-dev-ai",
"github_project": "drf-turbo",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [],
"lcname": "drf-turbo"
}