saritasa-drf-tools 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- saritasa_drf_tools-0.1.0/LICENCE +20 -0
- saritasa_drf_tools-0.1.0/PKG-INFO +313 -0
- saritasa_drf_tools-0.1.0/README.md +276 -0
- saritasa_drf_tools-0.1.0/pyproject.toml +325 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/__init__.py +0 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/filters/__init__.py +3 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/filters/django_filters.py +32 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/filters/ordering.py +71 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/filters/search.py +74 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/open_api/__init__.py +2 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/open_api/extend_schema.py +28 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/open_api/serializers.py +27 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/pagination.py +16 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/pytest_plugin.py +54 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/renderers.py +55 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/serializers/__init__.py +3 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/serializers/base.py +10 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/serializers/mixins/__init__.py +3 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/serializers/mixins/clean_validation_mixin.py +106 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/serializers/mixins/field_mapping_override_mixin.py +31 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/serializers/mixins/user_and_request_from_request_mixin.py +15 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/serializers/model_base.py +12 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/testing/__init__.py +10 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/testing/api_action_tester.py +257 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/testing/drf_standardized_errors.py +22 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/views/__init__.py +4 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/views/base.py +11 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/views/crud.py +14 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/views/mixins/__init__.py +3 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/views/mixins/permissions_map_mixin.py +162 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/views/mixins/serializers_map_mixin.py +45 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/views/mixins/update_without_patch_mixin.py +14 -0
- saritasa_drf_tools-0.1.0/saritasa_drf_tools/views/read_only.py +11 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
Copyright (c) 2025 Saritasa
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
in the Software without restriction, including without limitation the rights
|
|
7
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
furnished to do so, subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
17
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
18
|
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
19
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
|
20
|
+
OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: saritasa-drf-tools
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tools For DRF Used By Saritasa
|
|
5
|
+
License: MIT
|
|
6
|
+
Keywords: python,django,drf
|
|
7
|
+
Author: Saritasa
|
|
8
|
+
Author-email: pypi@saritasa.com
|
|
9
|
+
Maintainer: Stanislav Khlud
|
|
10
|
+
Maintainer-email: stanislav.khlud@saritasa.com
|
|
11
|
+
Requires-Python: >=3.12,<4.0
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: Django
|
|
14
|
+
Classifier: Framework :: Django :: 4.2
|
|
15
|
+
Classifier: Framework :: Django :: 5.0
|
|
16
|
+
Classifier: Framework :: Django :: 5.1
|
|
17
|
+
Classifier: Framework :: Pytest
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
20
|
+
Classifier: Natural Language :: English
|
|
21
|
+
Classifier: Operating System :: OS Independent
|
|
22
|
+
Classifier: Programming Language :: Python :: 3
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
26
|
+
Provides-Extra: all
|
|
27
|
+
Provides-Extra: filter
|
|
28
|
+
Provides-Extra: openapi
|
|
29
|
+
Requires-Dist: django (<6)
|
|
30
|
+
Requires-Dist: django-filter (<26) ; extra == "filter" or extra == "all"
|
|
31
|
+
Requires-Dist: djangorestframework (<4)
|
|
32
|
+
Requires-Dist: drf-spectacular (<1) ; extra == "openapi" or extra == "all"
|
|
33
|
+
Project-URL: Homepage, https://pypi.org/project/saritasa-drf-tools/
|
|
34
|
+
Project-URL: Repository, https://github.com/saritasa-nest/saritasa-drf-tools/
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# saritasa-drf-tools
|
|
38
|
+
|
|
39
|
+

|
|
40
|
+
[](https://pypi.org/project/saritasa-drf-tools/)
|
|
41
|
+

|
|
42
|
+

|
|
43
|
+

|
|
44
|
+

|
|
45
|
+

|
|
46
|
+
[](https://github.com/astral-sh/ruff)
|
|
47
|
+
|
|
48
|
+
Tools For [DRF](https://www.django-rest-framework.org/) Used By Saritasa
|
|
49
|
+
|
|
50
|
+
## Table of contents
|
|
51
|
+
|
|
52
|
+
* [Installation](#installation)
|
|
53
|
+
* [Features](#features)
|
|
54
|
+
* [Optional dependencies](#optional-dependencies)
|
|
55
|
+
* [Serializers](#serializers)
|
|
56
|
+
* [Views](#views)
|
|
57
|
+
* [Pagination](#pagination)
|
|
58
|
+
* [Filters](#filters)
|
|
59
|
+
* [Renderers](#renderers)
|
|
60
|
+
* [OpenAPI](#openapi)
|
|
61
|
+
* [Tester](#tester)
|
|
62
|
+
|
|
63
|
+
## Installation
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install saritasa-drf-tools
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
or if you are using [uv](https://docs.astral.sh/uv/)
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
uv add saritasa-drf-tools
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
or if you are using [poetry](https://python-poetry.org/)
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
poetry add saritasa-drf-tools
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Features
|
|
82
|
+
|
|
83
|
+
* Views - collection of mixins and viewsets classes
|
|
84
|
+
* Serializers - collection of mixins and serializers classes
|
|
85
|
+
* Filters - Custom filter backends that improve integration with
|
|
86
|
+
[drf-spectacular](https://github.com/tfranzel/drf-spectacular)
|
|
87
|
+
* OpenAPI - tools for [drf-spectacular](https://github.com/tfranzel/drf-spectacular)
|
|
88
|
+
* `pytest` - plugin which provides different `api_client` fixtures.
|
|
89
|
+
* Testing classes(**Warning: Very experimental**) - Test class which contains shortcut to reduce boilerplate across tests.
|
|
90
|
+
|
|
91
|
+
For examples and to just check it out in action you can use [example folder](/example).
|
|
92
|
+
|
|
93
|
+
## Optional dependencies
|
|
94
|
+
|
|
95
|
+
* `[filters]` - Add this to enable `django-filters` support
|
|
96
|
+
* `[openapi]` - Add this to enable `drf-spectacular` support
|
|
97
|
+
|
|
98
|
+
## Views
|
|
99
|
+
|
|
100
|
+
### Views mixins
|
|
101
|
+
|
|
102
|
+
* `ActionPermissionsMixin`: Mixin which allows to define specific permissions per actions
|
|
103
|
+
For example you have:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
class CRUDView(
|
|
107
|
+
ActionPermissionsMixin,
|
|
108
|
+
ActionMixins, # Anything you need
|
|
109
|
+
GenericViewSet,
|
|
110
|
+
):
|
|
111
|
+
"""CRUD view."""
|
|
112
|
+
base_permission_classes = (permissions.AllowAny,)
|
|
113
|
+
extra_permission_classes = (permissions.IsAuthenticated,)
|
|
114
|
+
extra_permissions_map = {
|
|
115
|
+
"create": (permissions.IsAdminUser,),
|
|
116
|
+
"update": (permissions.IsAdminUser,),
|
|
117
|
+
"destroy": (permissions.IsAdminUser,),
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
* `base_permission_classes` - Will be applied to any action (Usually you want this in base class of your project)
|
|
122
|
+
* `extra_permission_classes` - Will be added to `base_permission_classes`
|
|
123
|
+
* `extra_permission_map` - Will be added to (`base_permission_classes` + `extra_permission_classes`) on
|
|
124
|
+
action you specify in mapping
|
|
125
|
+
|
|
126
|
+
To learn more read class docs.
|
|
127
|
+
|
|
128
|
+
* `ActionSerializerMixin`: Mixin which allows to define specific serializers per action.
|
|
129
|
+
For example you have
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
class CRUDView(
|
|
133
|
+
ActionPermissionsMixin,
|
|
134
|
+
ActionMixins, # Anything you need
|
|
135
|
+
GenericViewSet,
|
|
136
|
+
):
|
|
137
|
+
"""CRUD view."""
|
|
138
|
+
|
|
139
|
+
queryset = models.TestModel.objects.select_related("related_model").all()
|
|
140
|
+
serializers_map = {
|
|
141
|
+
"default": serializers.TestModelDetailSerializer,
|
|
142
|
+
"list": serializers.TestModelListSerializer,
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
That means that on `list` view will use `TestModelListSerializer`, but on any other
|
|
147
|
+
actions `TestModelDetailSerializer`. This will also will be reflected in
|
|
148
|
+
generated openapi specs via [drf-spectacular](https://github.com/tfranzel/drf-spectacular)
|
|
149
|
+
|
|
150
|
+
To learn more read class docs.
|
|
151
|
+
|
|
152
|
+
* `UpdateModelWithoutPatchMixin`: Same as UpdateModelMixin but without patch method
|
|
153
|
+
|
|
154
|
+
### Viewset classes
|
|
155
|
+
|
|
156
|
+
* `BaseViewSet`: Viewset with `ActionPermissionsMixin` and `ActionSerializerMixin`
|
|
157
|
+
* `CRUDViewSet`: Viewset with crud endpoint based on BaseViewSet
|
|
158
|
+
* `ReadOnlyViewSet`: Viewset with read endpoint based on BaseViewSet
|
|
159
|
+
|
|
160
|
+
## Pagination
|
|
161
|
+
|
|
162
|
+
* `LimitOffsetPagination`: Customized paginator class to limit max objects in list APIs.
|
|
163
|
+
Use `SARITASA_DRF_MAX_PAGINATION_SIZE` to set default max for whole project.
|
|
164
|
+
|
|
165
|
+
## Serializers
|
|
166
|
+
|
|
167
|
+
### Serializers mixins
|
|
168
|
+
|
|
169
|
+
* `CleanValidationMixin`: Enable model `clean` validation in serializer
|
|
170
|
+
* `FieldMappingOverride`: Override or extend field mapping via `SARITASA_DRF_FIELD_MAPPING`.
|
|
171
|
+
For example you can set following in settings.
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
SARITASA_DRF_FIELD_MAPPING = {
|
|
175
|
+
"django.db.models.TextField": "example.app.api.fields.CustomCharField",
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
And now all `TextField` of your models will have `CustomCharField` in
|
|
180
|
+
serializers.
|
|
181
|
+
|
|
182
|
+
* `UserAndRequestFromContextMixin`: Extracts user and request from context
|
|
183
|
+
and sets it as attr of serializer instance.
|
|
184
|
+
|
|
185
|
+
### Serializers classes
|
|
186
|
+
|
|
187
|
+
* `BaseSerializer`: Serializer with `UserAndRequestFromContextMixin`
|
|
188
|
+
* `ModelBaseSerializer`: ModelSerializer with `mixins.FieldMappingOverride`,
|
|
189
|
+
`mixins.CleanValidationMixin`, `mixins.UserAndRequestFromContextMixin`.
|
|
190
|
+
|
|
191
|
+
## Filters
|
|
192
|
+
|
|
193
|
+
Needs `filters` and `openapi` to be included to work properly.
|
|
194
|
+
|
|
195
|
+
* `OrderingFilterBackend`: Add supported fields to `ordering` param's description
|
|
196
|
+
in specs generated by [drf-spectacular](https://github.com/tfranzel/drf-spectacular). Will raise warning specs validation
|
|
197
|
+
on empty `ordering_fields` or if queryset is unable to order itself using `ordering_fields`.
|
|
198
|
+
Example of description:
|
|
199
|
+
|
|
200
|
+
```text
|
|
201
|
+
Which fields to use when ordering the results. A list fields separated by ,. Example: field1,field2
|
|
202
|
+
|
|
203
|
+
Supported fields: id, text_field, related_model__text_field.
|
|
204
|
+
|
|
205
|
+
To reverse order just add - to field. Example:field -> -field
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
* `SearchFilterBackend`: Add supported fields to `search` param's description
|
|
209
|
+
in specs generated by [drf-spectacular](https://github.com/tfranzel/drf-spectacular). Will raise warning specs validation
|
|
210
|
+
on empty `search_fields` or if queryset is unable to perform search using `search_fields`.
|
|
211
|
+
|
|
212
|
+
Example of description:
|
|
213
|
+
|
|
214
|
+
```text
|
|
215
|
+
A search term.
|
|
216
|
+
|
|
217
|
+
Performed on this fields: text_field, related_model__text_field.
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
* `DjangoFilterBackend`: Customized `DjangoFilterBackend` to reduce queries count when viewing api requests via browser
|
|
221
|
+
|
|
222
|
+
## Renderers
|
|
223
|
+
|
|
224
|
+
* `BrowsableAPIRenderer`: Customization over drf's BrowsableAPIRenderer.
|
|
225
|
+
With `SARITASA_DRF_BROWSABLE_API_ENABLE_HTML_FORM`(Default: `True`) or
|
|
226
|
+
setting `enable_browsable_api_rendered_html_form`(If not present will use global setting)
|
|
227
|
+
in view you can disable all extra forms which results in extra SQL queries.
|
|
228
|
+
|
|
229
|
+
## OpenAPI
|
|
230
|
+
|
|
231
|
+
Needs `openapi` to be included to work properly.
|
|
232
|
+
|
|
233
|
+
* `OpenApiSerializer`: Serializer that should be used for customizing open_api spec.
|
|
234
|
+
Made to avoid warnings about unimplemented methods.
|
|
235
|
+
* `DetailSerializer`: To show in spec responses like this `{detail: text}`.
|
|
236
|
+
* `fix_api_view_warning`: Fix warning `This is graceful fallback handling for APIViews`.
|
|
237
|
+
|
|
238
|
+
## Pytest
|
|
239
|
+
|
|
240
|
+
Plugin provides following fixtures:
|
|
241
|
+
|
|
242
|
+
* `api_client_factory` - factory which generated `rest_framework.test.ApiClient` instance
|
|
243
|
+
* `api_client` - uses `api_client_factory` to generate `rest_framework.test.ApiClient` instance
|
|
244
|
+
* `user_api_client`(Needs `user` fixture) uses `api_client_factory` to generate `rest_framework.test.ApiClient` instance
|
|
245
|
+
forces auth to `user`
|
|
246
|
+
* `admin_api_client`(Needs `admin` fixture) uses `api_client_factory` to generate `rest_framework.test.ApiClient` instance
|
|
247
|
+
forces auth to `admin`
|
|
248
|
+
|
|
249
|
+
## Tester
|
|
250
|
+
|
|
251
|
+
**Warning**: Very experimental.
|
|
252
|
+
|
|
253
|
+
`saritasa_drf_tools.testing.ApiActionTester` - is a tester class which contains
|
|
254
|
+
fixtures and shortcuts to simply and reduce boilerplate in tests for viewsets.
|
|
255
|
+
|
|
256
|
+
All you need to is create `tester.py`(you what ever you want it's just recommendation).
|
|
257
|
+
In this file declare new class which inherits `ApiActionTester`.
|
|
258
|
+
|
|
259
|
+
```python
|
|
260
|
+
class CRUDApiActionTester(
|
|
261
|
+
saritasa_drf_tools.testing.ApiActionTester.init_subclass(
|
|
262
|
+
model=models.TestModel, # Model of queryset in viewset
|
|
263
|
+
user_model=models.User, # Model of user used across project
|
|
264
|
+
factory=factories.TestModelFactory, # Factory which is used to generate instances for model
|
|
265
|
+
api_view=api.views.CRUDView, # Class of viewset against which we will be writing tests
|
|
266
|
+
url_basename="crud-api", # Base name of urls of viewset. {url_basename}-{action}
|
|
267
|
+
),
|
|
268
|
+
):
|
|
269
|
+
"""Tester for crud API."""
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Next you can write test just like this. (For more examples check this [folder](tests/test_crud_api))
|
|
273
|
+
|
|
274
|
+
```python
|
|
275
|
+
class TestCRUD(tester.CRUDApiActionTester):
|
|
276
|
+
"""Define tests."""
|
|
277
|
+
|
|
278
|
+
@pytest.mark.parametrize(
|
|
279
|
+
argnames=[
|
|
280
|
+
"parametrize_user",
|
|
281
|
+
"status_code",
|
|
282
|
+
],
|
|
283
|
+
argvalues=[
|
|
284
|
+
[
|
|
285
|
+
None,
|
|
286
|
+
status.HTTP_403_FORBIDDEN,
|
|
287
|
+
],
|
|
288
|
+
[
|
|
289
|
+
pytest_lazy_fixtures.lf("user"),
|
|
290
|
+
status.HTTP_403_FORBIDDEN,
|
|
291
|
+
],
|
|
292
|
+
[
|
|
293
|
+
pytest_lazy_fixtures.lf("admin"),
|
|
294
|
+
status.HTTP_201_CREATED,
|
|
295
|
+
],
|
|
296
|
+
],
|
|
297
|
+
)
|
|
298
|
+
def test_permission_map_specified_action_create(
|
|
299
|
+
self,
|
|
300
|
+
instance: tester.CRUDApiActionTester.model,
|
|
301
|
+
parametrize_user: tester.CRUDApiActionTester.user_model | None,
|
|
302
|
+
status_code: int,
|
|
303
|
+
) -> None:
|
|
304
|
+
"""Test that create action will properly handle permissions."""
|
|
305
|
+
self.make_request(
|
|
306
|
+
method="post",
|
|
307
|
+
user=parametrize_user,
|
|
308
|
+
expected_status=status_code,
|
|
309
|
+
path=self.lazy_url(action="list"),
|
|
310
|
+
data=self.serialize_data(action="create", data=instance),
|
|
311
|
+
)
|
|
312
|
+
```
|
|
313
|
+
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
# saritasa-drf-tools
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+
[](https://pypi.org/project/saritasa-drf-tools/)
|
|
5
|
+

|
|
6
|
+

|
|
7
|
+

|
|
8
|
+

|
|
9
|
+

|
|
10
|
+
[](https://github.com/astral-sh/ruff)
|
|
11
|
+
|
|
12
|
+
Tools For [DRF](https://www.django-rest-framework.org/) Used By Saritasa
|
|
13
|
+
|
|
14
|
+
## Table of contents
|
|
15
|
+
|
|
16
|
+
* [Installation](#installation)
|
|
17
|
+
* [Features](#features)
|
|
18
|
+
* [Optional dependencies](#optional-dependencies)
|
|
19
|
+
* [Serializers](#serializers)
|
|
20
|
+
* [Views](#views)
|
|
21
|
+
* [Pagination](#pagination)
|
|
22
|
+
* [Filters](#filters)
|
|
23
|
+
* [Renderers](#renderers)
|
|
24
|
+
* [OpenAPI](#openapi)
|
|
25
|
+
* [Tester](#tester)
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install saritasa-drf-tools
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
or if you are using [uv](https://docs.astral.sh/uv/)
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
uv add saritasa-drf-tools
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
or if you are using [poetry](https://python-poetry.org/)
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
poetry add saritasa-drf-tools
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Features
|
|
46
|
+
|
|
47
|
+
* Views - collection of mixins and viewsets classes
|
|
48
|
+
* Serializers - collection of mixins and serializers classes
|
|
49
|
+
* Filters - Custom filter backends that improve integration with
|
|
50
|
+
[drf-spectacular](https://github.com/tfranzel/drf-spectacular)
|
|
51
|
+
* OpenAPI - tools for [drf-spectacular](https://github.com/tfranzel/drf-spectacular)
|
|
52
|
+
* `pytest` - plugin which provides different `api_client` fixtures.
|
|
53
|
+
* Testing classes(**Warning: Very experimental**) - Test class which contains shortcut to reduce boilerplate across tests.
|
|
54
|
+
|
|
55
|
+
For examples and to just check it out in action you can use [example folder](/example).
|
|
56
|
+
|
|
57
|
+
## Optional dependencies
|
|
58
|
+
|
|
59
|
+
* `[filters]` - Add this to enable `django-filters` support
|
|
60
|
+
* `[openapi]` - Add this to enable `drf-spectacular` support
|
|
61
|
+
|
|
62
|
+
## Views
|
|
63
|
+
|
|
64
|
+
### Views mixins
|
|
65
|
+
|
|
66
|
+
* `ActionPermissionsMixin`: Mixin which allows to define specific permissions per actions
|
|
67
|
+
For example you have:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
class CRUDView(
|
|
71
|
+
ActionPermissionsMixin,
|
|
72
|
+
ActionMixins, # Anything you need
|
|
73
|
+
GenericViewSet,
|
|
74
|
+
):
|
|
75
|
+
"""CRUD view."""
|
|
76
|
+
base_permission_classes = (permissions.AllowAny,)
|
|
77
|
+
extra_permission_classes = (permissions.IsAuthenticated,)
|
|
78
|
+
extra_permissions_map = {
|
|
79
|
+
"create": (permissions.IsAdminUser,),
|
|
80
|
+
"update": (permissions.IsAdminUser,),
|
|
81
|
+
"destroy": (permissions.IsAdminUser,),
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
* `base_permission_classes` - Will be applied to any action (Usually you want this in base class of your project)
|
|
86
|
+
* `extra_permission_classes` - Will be added to `base_permission_classes`
|
|
87
|
+
* `extra_permission_map` - Will be added to (`base_permission_classes` + `extra_permission_classes`) on
|
|
88
|
+
action you specify in mapping
|
|
89
|
+
|
|
90
|
+
To learn more read class docs.
|
|
91
|
+
|
|
92
|
+
* `ActionSerializerMixin`: Mixin which allows to define specific serializers per action.
|
|
93
|
+
For example you have
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
class CRUDView(
|
|
97
|
+
ActionPermissionsMixin,
|
|
98
|
+
ActionMixins, # Anything you need
|
|
99
|
+
GenericViewSet,
|
|
100
|
+
):
|
|
101
|
+
"""CRUD view."""
|
|
102
|
+
|
|
103
|
+
queryset = models.TestModel.objects.select_related("related_model").all()
|
|
104
|
+
serializers_map = {
|
|
105
|
+
"default": serializers.TestModelDetailSerializer,
|
|
106
|
+
"list": serializers.TestModelListSerializer,
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
That means that on `list` view will use `TestModelListSerializer`, but on any other
|
|
111
|
+
actions `TestModelDetailSerializer`. This will also will be reflected in
|
|
112
|
+
generated openapi specs via [drf-spectacular](https://github.com/tfranzel/drf-spectacular)
|
|
113
|
+
|
|
114
|
+
To learn more read class docs.
|
|
115
|
+
|
|
116
|
+
* `UpdateModelWithoutPatchMixin`: Same as UpdateModelMixin but without patch method
|
|
117
|
+
|
|
118
|
+
### Viewset classes
|
|
119
|
+
|
|
120
|
+
* `BaseViewSet`: Viewset with `ActionPermissionsMixin` and `ActionSerializerMixin`
|
|
121
|
+
* `CRUDViewSet`: Viewset with crud endpoint based on BaseViewSet
|
|
122
|
+
* `ReadOnlyViewSet`: Viewset with read endpoint based on BaseViewSet
|
|
123
|
+
|
|
124
|
+
## Pagination
|
|
125
|
+
|
|
126
|
+
* `LimitOffsetPagination`: Customized paginator class to limit max objects in list APIs.
|
|
127
|
+
Use `SARITASA_DRF_MAX_PAGINATION_SIZE` to set default max for whole project.
|
|
128
|
+
|
|
129
|
+
## Serializers
|
|
130
|
+
|
|
131
|
+
### Serializers mixins
|
|
132
|
+
|
|
133
|
+
* `CleanValidationMixin`: Enable model `clean` validation in serializer
|
|
134
|
+
* `FieldMappingOverride`: Override or extend field mapping via `SARITASA_DRF_FIELD_MAPPING`.
|
|
135
|
+
For example you can set following in settings.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
SARITASA_DRF_FIELD_MAPPING = {
|
|
139
|
+
"django.db.models.TextField": "example.app.api.fields.CustomCharField",
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
And now all `TextField` of your models will have `CustomCharField` in
|
|
144
|
+
serializers.
|
|
145
|
+
|
|
146
|
+
* `UserAndRequestFromContextMixin`: Extracts user and request from context
|
|
147
|
+
and sets it as attr of serializer instance.
|
|
148
|
+
|
|
149
|
+
### Serializers classes
|
|
150
|
+
|
|
151
|
+
* `BaseSerializer`: Serializer with `UserAndRequestFromContextMixin`
|
|
152
|
+
* `ModelBaseSerializer`: ModelSerializer with `mixins.FieldMappingOverride`,
|
|
153
|
+
`mixins.CleanValidationMixin`, `mixins.UserAndRequestFromContextMixin`.
|
|
154
|
+
|
|
155
|
+
## Filters
|
|
156
|
+
|
|
157
|
+
Needs `filters` and `openapi` to be included to work properly.
|
|
158
|
+
|
|
159
|
+
* `OrderingFilterBackend`: Add supported fields to `ordering` param's description
|
|
160
|
+
in specs generated by [drf-spectacular](https://github.com/tfranzel/drf-spectacular). Will raise warning specs validation
|
|
161
|
+
on empty `ordering_fields` or if queryset is unable to order itself using `ordering_fields`.
|
|
162
|
+
Example of description:
|
|
163
|
+
|
|
164
|
+
```text
|
|
165
|
+
Which fields to use when ordering the results. A list fields separated by ,. Example: field1,field2
|
|
166
|
+
|
|
167
|
+
Supported fields: id, text_field, related_model__text_field.
|
|
168
|
+
|
|
169
|
+
To reverse order just add - to field. Example:field -> -field
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
* `SearchFilterBackend`: Add supported fields to `search` param's description
|
|
173
|
+
in specs generated by [drf-spectacular](https://github.com/tfranzel/drf-spectacular). Will raise warning specs validation
|
|
174
|
+
on empty `search_fields` or if queryset is unable to perform search using `search_fields`.
|
|
175
|
+
|
|
176
|
+
Example of description:
|
|
177
|
+
|
|
178
|
+
```text
|
|
179
|
+
A search term.
|
|
180
|
+
|
|
181
|
+
Performed on this fields: text_field, related_model__text_field.
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
* `DjangoFilterBackend`: Customized `DjangoFilterBackend` to reduce queries count when viewing api requests via browser
|
|
185
|
+
|
|
186
|
+
## Renderers
|
|
187
|
+
|
|
188
|
+
* `BrowsableAPIRenderer`: Customization over drf's BrowsableAPIRenderer.
|
|
189
|
+
With `SARITASA_DRF_BROWSABLE_API_ENABLE_HTML_FORM`(Default: `True`) or
|
|
190
|
+
setting `enable_browsable_api_rendered_html_form`(If not present will use global setting)
|
|
191
|
+
in view you can disable all extra forms which results in extra SQL queries.
|
|
192
|
+
|
|
193
|
+
## OpenAPI
|
|
194
|
+
|
|
195
|
+
Needs `openapi` to be included to work properly.
|
|
196
|
+
|
|
197
|
+
* `OpenApiSerializer`: Serializer that should be used for customizing open_api spec.
|
|
198
|
+
Made to avoid warnings about unimplemented methods.
|
|
199
|
+
* `DetailSerializer`: To show in spec responses like this `{detail: text}`.
|
|
200
|
+
* `fix_api_view_warning`: Fix warning `This is graceful fallback handling for APIViews`.
|
|
201
|
+
|
|
202
|
+
## Pytest
|
|
203
|
+
|
|
204
|
+
Plugin provides following fixtures:
|
|
205
|
+
|
|
206
|
+
* `api_client_factory` - factory which generated `rest_framework.test.ApiClient` instance
|
|
207
|
+
* `api_client` - uses `api_client_factory` to generate `rest_framework.test.ApiClient` instance
|
|
208
|
+
* `user_api_client`(Needs `user` fixture) uses `api_client_factory` to generate `rest_framework.test.ApiClient` instance
|
|
209
|
+
forces auth to `user`
|
|
210
|
+
* `admin_api_client`(Needs `admin` fixture) uses `api_client_factory` to generate `rest_framework.test.ApiClient` instance
|
|
211
|
+
forces auth to `admin`
|
|
212
|
+
|
|
213
|
+
## Tester
|
|
214
|
+
|
|
215
|
+
**Warning**: Very experimental.
|
|
216
|
+
|
|
217
|
+
`saritasa_drf_tools.testing.ApiActionTester` - is a tester class which contains
|
|
218
|
+
fixtures and shortcuts to simply and reduce boilerplate in tests for viewsets.
|
|
219
|
+
|
|
220
|
+
All you need to is create `tester.py`(you what ever you want it's just recommendation).
|
|
221
|
+
In this file declare new class which inherits `ApiActionTester`.
|
|
222
|
+
|
|
223
|
+
```python
|
|
224
|
+
class CRUDApiActionTester(
|
|
225
|
+
saritasa_drf_tools.testing.ApiActionTester.init_subclass(
|
|
226
|
+
model=models.TestModel, # Model of queryset in viewset
|
|
227
|
+
user_model=models.User, # Model of user used across project
|
|
228
|
+
factory=factories.TestModelFactory, # Factory which is used to generate instances for model
|
|
229
|
+
api_view=api.views.CRUDView, # Class of viewset against which we will be writing tests
|
|
230
|
+
url_basename="crud-api", # Base name of urls of viewset. {url_basename}-{action}
|
|
231
|
+
),
|
|
232
|
+
):
|
|
233
|
+
"""Tester for crud API."""
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Next you can write test just like this. (For more examples check this [folder](tests/test_crud_api))
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
class TestCRUD(tester.CRUDApiActionTester):
|
|
240
|
+
"""Define tests."""
|
|
241
|
+
|
|
242
|
+
@pytest.mark.parametrize(
|
|
243
|
+
argnames=[
|
|
244
|
+
"parametrize_user",
|
|
245
|
+
"status_code",
|
|
246
|
+
],
|
|
247
|
+
argvalues=[
|
|
248
|
+
[
|
|
249
|
+
None,
|
|
250
|
+
status.HTTP_403_FORBIDDEN,
|
|
251
|
+
],
|
|
252
|
+
[
|
|
253
|
+
pytest_lazy_fixtures.lf("user"),
|
|
254
|
+
status.HTTP_403_FORBIDDEN,
|
|
255
|
+
],
|
|
256
|
+
[
|
|
257
|
+
pytest_lazy_fixtures.lf("admin"),
|
|
258
|
+
status.HTTP_201_CREATED,
|
|
259
|
+
],
|
|
260
|
+
],
|
|
261
|
+
)
|
|
262
|
+
def test_permission_map_specified_action_create(
|
|
263
|
+
self,
|
|
264
|
+
instance: tester.CRUDApiActionTester.model,
|
|
265
|
+
parametrize_user: tester.CRUDApiActionTester.user_model | None,
|
|
266
|
+
status_code: int,
|
|
267
|
+
) -> None:
|
|
268
|
+
"""Test that create action will properly handle permissions."""
|
|
269
|
+
self.make_request(
|
|
270
|
+
method="post",
|
|
271
|
+
user=parametrize_user,
|
|
272
|
+
expected_status=status_code,
|
|
273
|
+
path=self.lazy_url(action="list"),
|
|
274
|
+
data=self.serialize_data(action="create", data=instance),
|
|
275
|
+
)
|
|
276
|
+
```
|