Tools For DRF Used By Saritasa
Project description
saritasa-drf-tools
Tools For DRF Used By Saritasa
Table of contents
- Installation
- Features
- Optional dependencies
- Serializers
- Views
- Pagination
- Filters
- Renderers
- OpenAPI
- Tester
Installation
pip install saritasa-drf-tools
or if you are using uv
uv add saritasa-drf-tools
or if you are using poetry
poetry add saritasa-drf-tools
Features
- Views - collection of mixins and viewsets classes
- Serializers - collection of mixins and serializers classes
- Filters - Custom filter backends that improve integration with drf-spectacular
- OpenAPI - tools for drf-spectacular
pytest- plugin which provides differentapi_clientfixtures.- Testing classes(Warning: Very experimental) - Test class which contains shortcut to reduce boilerplate across tests.
For examples and to just check it out in action you can use example folder.
Optional dependencies
[filters]- Add this to enabledjango-filterssupport[openapi]- Add this to enabledrf-spectacularsupport
Views
Views mixins
-
ActionPermissionsMixin: Mixin which allows to define specific permissions per actions For example you have:class CRUDView( ActionPermissionsMixin, ActionMixins, # Anything you need GenericViewSet, ): """CRUD view.""" base_permission_classes = (permissions.AllowAny,) extra_permission_classes = (permissions.IsAuthenticated,) extra_permissions_map = { "create": (permissions.IsAdminUser,), "update": (permissions.IsAdminUser,), "destroy": (permissions.IsAdminUser,), }
base_permission_classes- Will be applied to any action (Usually you want this in base class of your project)extra_permission_classes- Will be added tobase_permission_classesextra_permission_map- Will be added to (base_permission_classes+extra_permission_classes) on action you specify in mapping
To learn more read class docs.
-
ActionSerializerMixin: Mixin which allows to define specific serializers per action. For example you haveclass CRUDView( ActionPermissionsMixin, ActionMixins, # Anything you need GenericViewSet, ): """CRUD view.""" queryset = models.TestModel.objects.select_related("related_model").all() serializers_map = { "default": serializers.TestModelDetailSerializer, "list": serializers.TestModelListSerializer, }
That means that on
listview will useTestModelListSerializer, but on any other actionsTestModelDetailSerializer. This will also will be reflected in generated openapi specs via drf-spectacularTo learn more read class docs.
-
UpdateModelWithoutPatchMixin: Same as UpdateModelMixin but without patch method
Viewset classes
BaseViewSet: Viewset withActionPermissionsMixinandActionSerializerMixinCRUDViewSet: Viewset with crud endpoint based on BaseViewSetReadOnlyViewSet: Viewset with read endpoint based on BaseViewSet
Pagination
LimitOffsetPagination: Customized paginator class to limit max objects in list APIs. UseSARITASA_DRF_MAX_PAGINATION_SIZEto set default max for whole project.
Serializers
Serializers mixins
-
CleanValidationMixin: Enable modelcleanvalidation in serializer -
FieldMappingOverride: Override or extend field mapping viaSARITASA_DRF_FIELD_MAPPING. For example you can set following in settings.SARITASA_DRF_FIELD_MAPPING = { "django.db.models.TextField": "example.app.api.fields.CustomCharField", }
And now all
TextFieldof your models will haveCustomCharFieldin serializers. -
UserAndRequestFromContextMixin: Extracts user and request from context and sets it as attr of serializer instance. -
NestedFieldsMixin: Allows to define nested data fields for serializers viaMetaclass.
Serializers classes
BaseSerializer: Serializer withUserAndRequestFromContextMixinModelBaseSerializer: ModelSerializer withmixins.FieldMappingOverride,mixins.CleanValidationMixin,mixins.UserAndRequestFromContextMixin,mixins.NestedFieldsMixin.
Filters
Needs filters and openapi to be included to work properly.
-
OrderingFilterBackend: Add supported fields toorderingparam's description in specs generated by drf-spectacular. Will raise warning specs validation on emptyordering_fieldsor if queryset is unable to order itself usingordering_fields. Example of description:Which fields to use when ordering the results. A list fields separated by ,. Example: field1,field2 Supported fields: id, text_field, related_model__text_field. To reverse order just add - to field. Example:field -> -field
Also has support for
nulls_firstandnulls_lastordering. You can either set these options globally in your settings:SARITASA_DRF_ORDERING_IS_NULL_FIRST = True SARITASA_DRF_ORDERING_IS_NULL_LAST = True
Or you can set them per view:
class MyView(views.APIView): ordering_fields_extra_kwargs = { "my_field": { "nulls_first": True, "nulls_last": False, }, }
-
SearchFilterBackend: Add supported fields tosearchparam's description in specs generated by drf-spectacular. Will raise warning specs validation on emptysearch_fieldsor if queryset is unable to perform search usingsearch_fields.Example of description:
A search term. Performed on this fields: text_field, related_model__text_field.
-
DjangoFilterBackend: CustomizedDjangoFilterBackendto reduce queries count when viewing api requests via browser
Renderers
BrowsableAPIRenderer: Customization over drf's BrowsableAPIRenderer. WithSARITASA_DRF_BROWSABLE_API_ENABLE_HTML_FORM(Default:True) or settingenable_browsable_api_rendered_html_form(If not present will use global setting) in view you can disable all extra forms which results in extra SQL queries.
OpenAPI
Needs openapi to be included to work properly.
OpenApiSerializer: Serializer that should be used for customizing open_api spec. Made to avoid warnings about unimplemented methods.DetailSerializer: To show in spec responses like this{detail: text}.fix_api_view_warning: Fix warningThis is graceful fallback handling for APIViews.
Pytest
Plugin provides following fixtures:
api_client_factory- factory which generatedrest_framework.test.ApiClientinstanceapi_client- usesapi_client_factoryto generaterest_framework.test.ApiClientinstanceuser_api_client(Needsuserfixture) usesapi_client_factoryto generaterest_framework.test.ApiClientinstance forces auth touseradmin_api_client(Needsadminfixture) usesapi_client_factoryto generaterest_framework.test.ApiClientinstance forces auth toadmin
Tester
Warning: Very experimental.
saritasa_drf_tools.testing.ApiActionTester - is a tester class which contains
fixtures and shortcuts to simply and reduce boilerplate in tests for viewsets.
All you need to is create tester.py(you what ever you want it's just recommendation).
In this file declare new class which inherits ApiActionTester.
class CRUDApiActionTester(
saritasa_drf_tools.testing.ApiActionTester.init_subclass(
model=models.TestModel, # Model of queryset in viewset
user_model=models.User, # Model of user used across project
factory=factories.TestModelFactory, # Factory which is used to generate instances for model
api_view=api.views.CRUDView, # Class of viewset against which we will be writing tests
url_basename="crud-api", # Base name of urls of viewset. {url_basename}-{action}
),
):
"""Tester for crud API."""
Next you can write test just like this. (For more examples check this folder)
class TestCRUD(tester.CRUDApiActionTester):
"""Define tests."""
@pytest.mark.parametrize(
argnames=[
"parametrize_user",
"status_code",
],
argvalues=[
[
None,
status.HTTP_403_FORBIDDEN,
],
[
pytest_lazy_fixtures.lf("user"),
status.HTTP_403_FORBIDDEN,
],
[
pytest_lazy_fixtures.lf("admin"),
status.HTTP_201_CREATED,
],
],
)
def test_permission_map_specified_action_create(
self,
instance: tester.CRUDApiActionTester.model,
parametrize_user: tester.CRUDApiActionTester.user_model | None,
status_code: int,
) -> None:
"""Test that create action will properly handle permissions."""
self.make_request(
method="post",
user=parametrize_user,
expected_status=status_code,
path=self.lazy_url(action="list"),
data=self.serialize_data(action="create", data=instance),
)
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file saritasa_drf_tools-0.2.2.tar.gz.
File metadata
- Download URL: saritasa_drf_tools-0.2.2.tar.gz
- Upload date:
- Size: 20.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.0 CPython/3.13.7 Linux/6.6.107-1-MANJARO
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6254f785fe19a1c253f9dbdc9a4d5f3a408ae35094deff9a4ef0c8bdab0e95e8
|
|
| MD5 |
de343038a357eaca4561acbdbb108270
|
|
| BLAKE2b-256 |
8d4a3be2b057d182314fc6bb6a93bc63a32ac5f6e30e09a94f7ef9409e2a5f88
|
File details
Details for the file saritasa_drf_tools-0.2.2-py3-none-any.whl.
File metadata
- Download URL: saritasa_drf_tools-0.2.2-py3-none-any.whl
- Upload date:
- Size: 26.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.0 CPython/3.13.7 Linux/6.6.107-1-MANJARO
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
10dbfb44748ba7758c67a60b0abc78e7cce60513846120efa448b50758efa780
|
|
| MD5 |
e8d1717c4614272ad4a3513940d36b5b
|
|
| BLAKE2b-256 |
86c368c73a3790e7a6e408c1d207db24c7bb632f9df2bc0eb27a51b9fa07d5be
|