djresttoolkit 0.17.0__py3-none-any.whl → 0.17.2__py3-none-any.whl

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.
Files changed (59) hide show
  1. {djresttoolkit-0.17.0.dist-info → djresttoolkit-0.17.2.dist-info}/METADATA +2 -2
  2. djresttoolkit-0.17.2.dist-info/RECORD +55 -0
  3. README.md +0 -1067
  4. demo/staticfiles/admin/img/LICENSE +0 -20
  5. djresttoolkit-0.17.0.dist-info/RECORD +0 -58
  6. djresttoolkit-0.17.0.dist-info/licenses/LICENSE +0 -23
  7. {src/djresttoolkit → djresttoolkit}/__init__.py +0 -0
  8. {src/djresttoolkit → djresttoolkit}/admin.py +0 -0
  9. {src/djresttoolkit → djresttoolkit}/apps.py +0 -0
  10. {src/djresttoolkit → djresttoolkit}/dbseed/__init__.py +0 -0
  11. {src/djresttoolkit → djresttoolkit}/dbseed/models/__init__.py +0 -0
  12. {src/djresttoolkit → djresttoolkit}/dbseed/models/_choice_field.py +0 -0
  13. {src/djresttoolkit → djresttoolkit}/dbseed/models/_gen.py +0 -0
  14. {src/djresttoolkit → djresttoolkit}/dbseed/models/_seed_model.py +0 -0
  15. {src/djresttoolkit → djresttoolkit}/envconfig/__init__.py +0 -0
  16. {src/djresttoolkit → djresttoolkit}/envconfig/_env_settings.py +0 -0
  17. {src/djresttoolkit → djresttoolkit}/mail/__init__.py +0 -0
  18. {src/djresttoolkit → djresttoolkit}/mail/_email_sender.py +0 -0
  19. {src/djresttoolkit → djresttoolkit}/mail/_models.py +0 -0
  20. {src/djresttoolkit → djresttoolkit}/mail/_types.py +0 -0
  21. {src/djresttoolkit → djresttoolkit}/management/__init__.py +0 -0
  22. {src/djresttoolkit → djresttoolkit}/management/commands/__init__.py +0 -0
  23. {src/djresttoolkit → djresttoolkit}/management/commands/dbflush.py +0 -0
  24. {src/djresttoolkit → djresttoolkit}/management/commands/dbseed.py +0 -0
  25. {src/djresttoolkit → djresttoolkit}/middlewares/__init__.py +0 -0
  26. {src/djresttoolkit → djresttoolkit}/middlewares/_response_time_middleware.py +0 -0
  27. {src/djresttoolkit → djresttoolkit}/migrations/__init__.py +0 -0
  28. {src/djresttoolkit → djresttoolkit}/models/__init__.py +0 -0
  29. {src/djresttoolkit → djresttoolkit}/models/mixins/__init__.py +0 -0
  30. {src/djresttoolkit → djresttoolkit}/models/mixins/_model_choice_fields_mixin.py +0 -0
  31. {src/djresttoolkit → djresttoolkit}/pagination/__init__.py +0 -0
  32. {src/djresttoolkit → djresttoolkit}/pagination/_page_number_pagination.py +0 -0
  33. {src/djresttoolkit → djresttoolkit}/pagination/_paginated_data_builder.py +0 -0
  34. {src/djresttoolkit → djresttoolkit}/py.typed +0 -0
  35. {src/djresttoolkit → djresttoolkit}/renderers/__init__.py +0 -0
  36. {src/djresttoolkit → djresttoolkit}/renderers/_throttle_info_json_renderer.py +0 -0
  37. {src/djresttoolkit → djresttoolkit}/serializers/__init__.py +0 -0
  38. {src/djresttoolkit → djresttoolkit}/serializers/mixins/__init__.py +0 -0
  39. {src/djresttoolkit → djresttoolkit}/serializers/mixins/_absolute_url_file_mixin.py +0 -0
  40. {src/djresttoolkit → djresttoolkit}/serializers/mixins/_bulk_create_mixin.py +0 -0
  41. {src/djresttoolkit → djresttoolkit}/throttling/__init__.py +0 -0
  42. {src/djresttoolkit → djresttoolkit}/throttling/_throttle_inspector.py +0 -0
  43. {src/djresttoolkit → djresttoolkit}/urls/__init__.py +0 -0
  44. {src/djresttoolkit → djresttoolkit}/urls/_build_absolute_uri.py +0 -0
  45. {src/djresttoolkit → djresttoolkit}/views/__init__.py +0 -0
  46. {src/djresttoolkit → djresttoolkit}/views/_api_views/__init__.py +0 -0
  47. {src/djresttoolkit → djresttoolkit}/views/_api_views/_choice_fields_apiview.py +0 -0
  48. {src/djresttoolkit → djresttoolkit}/views/_exceptions/__init__.py +0 -0
  49. {src/djresttoolkit → djresttoolkit}/views/_exceptions/_exception_handler.py +0 -0
  50. {src/djresttoolkit → djresttoolkit}/views/mixins/__init__.py +0 -0
  51. {src/djresttoolkit → djresttoolkit}/views/mixins/_cache_action_mixin.py +0 -0
  52. {src/djresttoolkit → djresttoolkit}/views/mixins/_cache_invalidate_mixin.py +0 -0
  53. {src/djresttoolkit → djresttoolkit}/views/mixins/_cache_key_mixin.py +0 -0
  54. {src/djresttoolkit → djresttoolkit}/views/mixins/_cache_list_retrieve_mixin.py +0 -0
  55. {src/djresttoolkit → djresttoolkit}/views/mixins/_cache_ops_mixin.py +0 -0
  56. {src/djresttoolkit → djresttoolkit}/views/mixins/_retrieve_object_mixin.py +0 -0
  57. {djresttoolkit-0.17.0.dist-info → djresttoolkit-0.17.2.dist-info}/WHEEL +0 -0
  58. {djresttoolkit-0.17.0.dist-info → djresttoolkit-0.17.2.dist-info}/entry_points.txt +0 -0
  59. /LICENSE → /djresttoolkit-0.17.2.dist-info/licenses/LICENSE +0 -0
README.md DELETED
@@ -1,1067 +0,0 @@
1
- # 🛠️ djresttoolkit (django rest toolkit)
2
-
3
- [![PyPI version](https://img.shields.io/pypi/v/djresttoolkit.svg)](https://pypi.org/project/djresttoolkit/)
4
- [![Python versions](https://img.shields.io/pypi/pyversions/djresttoolkit.svg)](https://pypi.org/project/djresttoolkit/)
5
- [![License](https://img.shields.io/pypi/l/djresttoolkit.svg)](https://github.com/shaileshpandit141/djresttoolkit/blob/main/LICENSE)
6
-
7
- djresttoolkit is a collection of utilities and helpers for Django and Django REST Framework (DRF) that simplify common development tasks such as API handling, authentication, and email sending and much more.
8
-
9
- ## 📖 Feature Index (djresttoolkit)
10
-
11
- - **DB Seed Command (`dbseed`)**
12
- Seed your database with fake data using Pydantic models powered by **Faker**. Supports relationships, transactions, and a `manage.py dbseed` command.
13
-
14
- - **DB Flush Command (`dbflush`)**
15
- Management command to flush all models or a specific model, resetting auto-increment IDs safely with transaction support.
16
-
17
- - **EnvBaseSettings**
18
- Typed settings loader using **YAML + .env**, supports nested keys and overrides. Great for structured configuration management.
19
-
20
- - **EmailSender**
21
- Custom class to send templated emails (`text` and `html`) with context. Supports error handling and logging.
22
-
23
- - **Custom DRF Exception Handler**
24
- Centralized error handler for DRF that extends default behavior and adds throttle support (`429 Too Many Requests` with retry info).
25
-
26
- - **Response Time Middleware**
27
- Middleware to measure, log, and inject `X-Response-Time` headers into every response.
28
-
29
- - **Throttle**
30
- - `ThrottleInfoJSONRenderer`: Automatically adds throttle headers to responses.
31
- - `ThrottleInspector`: Inspect view/request throttling and attach structured headers.
32
-
33
- - **AbsoluteUrlFileMixin**
34
- DRF serializer mixin that converts `FileField` / `ImageField` URLs to **absolute URLs** automatically.
35
-
36
- - **BulkCreateMixin**
37
- Serializer mixin that enables **bulk creation** of objects and syncs field error messages with model fields.
38
-
39
- - **ModelChoiceFieldMixin**
40
- Retrieve choice fields (`TextChoices`, etc.) from Django models as structured dictionaries for API responses.
41
-
42
- - **ChoiceFieldsAPIView**
43
- Generic API view that exposes model `choices` in a REST-friendly JSON format.
44
-
45
- - **RetrieveObjectMixin**
46
- Lightweight mixin to fetch a single object from a queryset with filters, raising a custom error if `queryset` is not defined.
47
-
48
- - **build\_absolute\_uri**
49
- Helper to build full absolute URLs for named routes with optional query params. Works with Django + DRF requests.
50
-
51
- - **PageNumberPagination**
52
- Custom paginator with a structured `"page"` metadata block and support for dynamic `page-size` query param.
53
-
54
- - **PaginatedDataBuilder**
55
- Builder that combines `PageNumberPagination` + serializers to return standardized paginated responses with `"page"` + `"results"`.
56
-
57
- - **Caching Mixins**
58
- This module provides a set of DRF mixins to handle caching for `list`, `retrieve`, and `custom actions` with automatic invalidation on create, update, and destroy.
59
-
60
- ## 📦 Installation
61
-
62
- - **By using uv:**
63
-
64
- ```bash
65
- uv add djresttoolkit
66
- ````
67
-
68
- - **By using pip:**
69
-
70
- ```bash
71
- pip install djresttoolkit
72
- ````
73
-
74
- ## 📚 All API Reference
75
-
76
- ### 1. DB Seed Command — API Reference
77
-
78
- #### `Generator`
79
-
80
- ```python
81
- from djresttoolkit.dbseed.models import Generator, Gen, Field
82
- ```
83
-
84
- - `Gen`: Pre-initialized **Faker** instance for generating fake data.
85
- - `Field`: Alias for `pydantic.Field` to define seed model fields.
86
-
87
- #### Example
88
-
89
- ```python
90
- from djresttoolkit.dbseed.models import SeedModel
91
- from myapp.models import User
92
-
93
- class UserSeedModel(SeedModel):
94
- __model__ = User
95
-
96
- username: str = Field(default_factory=lambda: Gen.user_name())
97
- email: str = Field(default_factory=lambda: Gen.email())
98
- ```
99
-
100
- #### `manage.py` Command: `dbseed`
101
-
102
- Seed the database from all `dbseed` directories in installed apps.
103
-
104
- ```bash
105
- python manage.py dbseed [--count 5] [--model User] [--seed 42]
106
- ```
107
-
108
- #### Options
109
-
110
- - `--count`: Number of records per model (default: 5).
111
- - `--model`: Specific model name to seed (optional).
112
- - `--seed`: Faker seed for reproducible data (optional).
113
-
114
- #### Behavior
115
-
116
- - Auto-discovers all `dbseed` models in installed apps.
117
- - Handles ForeignKey, OneToOneField, and ManyToMany relationships.
118
- - Uses transactions to ensure safe creation of records.
119
- - Logs errors for failed instance creation but continues seeding.
120
-
121
- #### Command Example
122
-
123
- ```bash
124
- # Seed 10 records for all models
125
- python manage.py dbseed --count 10
126
-
127
- # Seed only the User model with fixed Faker seed
128
- python manage.py dbseed --model User --seed 42
129
- ```
130
-
131
- Here’s a **concise API reference** for your database flush management command for `djresttoolkit`:
132
-
133
- ---
134
-
135
- ### 2. DB Flush Command — API Reference
136
-
137
- ```python
138
- from djresttoolkit.management.commands import flush
139
- ```
140
-
141
- #### `manage.py dbflush`
142
-
143
- Command to **delete all records** from the database for all models or a specific model and **reset auto-increment IDs**.
144
-
145
- #### Usage
146
-
147
- ```bash
148
- python manage.py flush [--model ModelName] [--yes]
149
- ```
150
-
151
- #### dbflush command options
152
-
153
- - `--model`: Name of the model to flush (case-sensitive, e.g., `User`). If omitted, flushes all models.
154
- - `--yes`: Skip confirmation prompt. Without this, the command asks for confirmation before deleting.
155
-
156
- #### dbflush command behavior
157
-
158
- - Deletes all records for the specified model or all models.
159
- - Resets primary key sequences for supported databases:
160
-
161
- - PostgreSQL: `ALTER SEQUENCE ... RESTART WITH 1`
162
- - SQLite: Deletes from `sqlite_sequence` table
163
- - Others: Logs a warning (not implemented).
164
- - Uses transactions to ensure safe operations.
165
-
166
- #### dbflush command example
167
-
168
- ```bash
169
- # Flush all models with confirmation
170
- python manage.py dbflush
171
-
172
- # Flush a specific model (User) with confirmation
173
- python manage.py dbflush --model User
174
-
175
- # Flush all models without prompt
176
- python manage.py dbflush --yes
177
- ```
178
-
179
- #### Output
180
-
181
- ```bash
182
- Flushed 10 records from model "User" and reset IDs.
183
- ```
184
-
185
- or
186
-
187
- ```bash
188
- Flushed 120 records from all models and reset IDs.
189
- ```
190
-
191
- ### 3. EnvBaseSettings — API Reference
192
-
193
- ```python
194
- from djresttoolkit.envconfig import EnvBaseSettings
195
- ```
196
-
197
- #### `EnvBaseSettings`
198
-
199
- A **base settings class** for managing application configuration using:
200
-
201
- - YAML files (default `.environ.yaml`)
202
- - Environment variables (default `.env`)
203
-
204
- Supports **nested configuration** using double underscores (`__`) in environment variable names.
205
-
206
- #### Class Attributes
207
-
208
- - Attributes
209
- - `env_file`
210
- - Type: `str`
211
- - Default: `.env`
212
- - Description: Environment variable file path.
213
- - `yaml_file`
214
- - Type: `str`
215
- - Default: `.environ.yaml`
216
- - Description: YAML configuration file path.
217
- - `model_config`
218
- - Type: `SettingsConfigDict`
219
- - Description: Pydantic settings configuration (file encoding, nested delimiter).
220
-
221
- #### Methods
222
-
223
- #### `load(cls, *, env_file: str | None = None, ymal_file: str | None = None, warning: bool = True) -> EnvBaseSettings`
224
-
225
- Loads configuration from **YAML first**, then overrides with **environment variables**.
226
-
227
- #### Parameters
228
-
229
- - `env_file` — Optional custom `.env` file path.
230
- - `ymal_file` — Optional custom YAML file path.
231
- - `warning` — Emit a warning if YAML file is missing (default `True`).
232
-
233
- #### Returns
234
-
235
- - Instance of `EnvBaseSettings` (or subclass) with loaded configuration.
236
-
237
- #### Raises
238
-
239
- - `UserWarning` if YAML file not found and `warning=True`.
240
-
241
- ### Usage Example
242
-
243
- ```python
244
- from djresttoolkit.envconfig import EnvBaseSettings
245
-
246
- class EnvSettings(EnvBaseSettings["EnvSettings"]):
247
- debug: bool = False
248
- database_url: str
249
-
250
- # Load settings
251
- settings = EnvSettings.load(warning=False)
252
-
253
- print(settings.debug)
254
- print(settings.database_url)
255
- ```
256
-
257
- #### Features
258
-
259
- - Prioritizes `.env` variables over YAML.
260
- - Supports nested keys: `DATABASE__HOST`:- `settings.database.host`.
261
- - Designed to be subclassed for project-specific settings.
262
-
263
- ### 4. EmailSender — API Reference
264
-
265
- ```python
266
- from djresttoolkit.mail import EmailSender, EmailContent, EmailTemplate
267
- ```
268
-
269
- ### `EmailSender`
270
-
271
- Send templated emails.
272
-
273
- #### Init
274
-
275
- ```python
276
- EmailSender(email_content: EmailContent | EmailContentDict)
277
- ```
278
-
279
- #### EmailSender Methods
280
-
281
- ```python
282
- send(to: list[str], exceptions: bool = False) -> bool
283
- ```
284
-
285
- - `to`: recipient emails
286
- - `exceptions`: raise on error if `True`, else logs error
287
- - Returns `True` if sent, `False` on failure
288
-
289
- #### Example for sending an email
290
-
291
- ```python
292
- content = EmailContent(
293
- subject="Hello",
294
- from_email="noreply@example.com",
295
- context={"username": "Alice"},
296
- template=EmailTemplate(
297
- text="emails/welcome.txt",
298
- html="emails/welcome.html"
299
- )
300
- )
301
- EmailSender(content).send(to=["user@example.com"])
302
- ```
303
-
304
- #### `EmailContent`
305
-
306
- - `subject`, `from_email`, `context`, `template` (EmailTemplate)
307
-
308
- #### `EmailTemplate`
309
-
310
- - `text`, `html` — template file paths
311
-
312
- ### 5. Custom DRF Exception Handler — API Reference
313
-
314
- ```python
315
- from djresttoolkit.views import exception_handler
316
- ```
317
-
318
- ### `exception_handler(exc: Exception, context: dict[str, Any]) -> Response | None`
319
-
320
- A DRF exception handler that:
321
-
322
- - Preserves DRF’s default exception behavior.
323
- - Adds throttling support (defaults to `AnonRateThrottle`).
324
- - Returns **429 Too Many Requests** with `retry_after` if throttle limit is exceeded.
325
-
326
- #### Exception Handler Parameters
327
-
328
- - `exc`: Exception object.
329
- - `context`: DRF context dictionary containing `"request"` and `"view"`.
330
-
331
- #### Returns Type of Exception Handler
332
-
333
- - `Response` — DRF Response object (with throttling info if applicable), or `None`.
334
-
335
- #### Settings Configuration
336
-
337
- In `settings.py`:
338
-
339
- ```python
340
- REST_FRAMEWORK = {
341
- 'EXCEPTION_HANDLER': 'djresttoolkit.views.exception_handler',
342
- # Other DRF settings...
343
- }
344
- ```
345
-
346
- #### Throttle Behavior
347
-
348
- - Uses `view.throttle_classes` if defined, else defaults to `AnonRateThrottle`.
349
- - Tracks requests in cache and calculates `retry_after`.
350
- - Cleans expired timestamps automatically.
351
-
352
- ### 6. Response Time Middleware — API Reference
353
-
354
- ```python
355
- from djresttoolkit.middlewares import ResponseTimeMiddleware
356
- ```
357
-
358
- ### `ResponseTimeMiddleware`
359
-
360
- Middleware to calculate and log **HTTP response time** for each request.
361
-
362
- #### Constructor from ResponseTimeMiddleware
363
-
364
- ```python
365
- ResponseTimeMiddleware(get_response: Callable[[HttpRequest], HttpResponse])
366
- ```
367
-
368
- - `get_response`: The next middleware or view callable.
369
-
370
- #### Response Time Middleware Usage
371
-
372
- Add it to your Django `MIDDLEWARE` in `settings.py`:
373
-
374
- ```python
375
- MIDDLEWARE = [
376
- # Other middlewares...
377
- 'djresttoolkit.middlewares.ResponseTimeMiddleware',
378
- ]
379
- ```
380
-
381
- #### Response Time Middleware Behavior
382
-
383
- - Measures the time taken to process each request.
384
- - Adds a header `X-Response-Time` to each HTTP response.
385
- - Logs the response time using Django's logging system.
386
-
387
- #### The response headers will include
388
-
389
- ```json
390
- X-Response-Time: 0.01234 seconds
391
- ```
392
-
393
- #### Logs a message
394
-
395
- ```bash
396
- INFO: Request processed in 0.01234 seconds
397
- ```
398
-
399
- ### 7. Throttle — API Reference
400
-
401
- #### `ThrottleInfoJSONRenderer`
402
-
403
- ```python
404
- from djresttoolkit.renderers import ThrottleInfoJSONRenderer
405
- ```
406
-
407
- A custom DRF JSON renderer that **automatically attaches throttle information to response headers**.
408
-
409
- #### Usage (settings.py)
410
-
411
- ```python
412
- REST_FRAMEWORK = {
413
- "DEFAULT_RENDERER_CLASSES": [
414
- "djresttoolkit.renderers.ThrottleInfoJSONRenderer",
415
- "rest_framework.renderers.BrowsableAPIRenderer",
416
- ],
417
- }
418
- ```
419
-
420
- When enabled, every response includes throttle headers like:
421
-
422
- ```plaintext
423
- X-Throttle-User-Limit: 100
424
- X-Throttle-User-Remaining: 98
425
- X-Throttle-User-Reset: 2025-08-18T07:30:00Z
426
- X-Throttle-User-Retry-After: 0
427
- ```
428
-
429
- #### `ThrottleInspector`
430
-
431
- ```python
432
- from djresttoolkit.throttling import ThrottleInspector
433
- ```
434
-
435
- Utility class to **inspect DRF throttle usage** for a view or request.
436
-
437
- #### Constructor for ThrottleInspector
438
-
439
- ```python
440
- ThrottleInspector(
441
- view: APIView,
442
- request: Request | None = None,
443
- throttle_classes: list[type[BaseThrottle]] | None = None,
444
- )
445
- ```
446
-
447
- #### Key Methods
448
-
449
- - `get_details() -> dict[str, Any]`
450
- Returns structured throttle info: limit, remaining, reset time, retry\_after.
451
-
452
- - `attach_headers(response: Response, throttle_info: dict | None)`
453
- Attaches throttle data to HTTP headers.
454
-
455
- ### 8. AbsoluteUrlFileMixin — API Reference
456
-
457
- ```python
458
- from djresttoolkit.serializers.mixins import AbsoluteUrlFileMixin
459
- ```
460
-
461
- ### `AbsoluteUrlFileMixin`
462
-
463
- A **serializer mixin** that converts **FileField** and **ImageField** URLs to **absolute URLs**, ensuring compatibility with cloud storage backends.
464
-
465
- ---
466
-
467
- ### Attributes
468
-
469
- - `file_fields`
470
- - type: `list[str] | None`
471
- - default: `None`
472
- - description: Manual list of file field names for non-model serializers.
473
-
474
- ### Absolute Url File Mixin Methods
475
-
476
- #### `to_representation(self, instance: Any) -> dict[str, Any]`
477
-
478
- - Overrides default serializer `to_representation`.
479
- - Enhances all file-related fields in the serialized output to **absolute URLs**.
480
-
481
- #### `enhance_file_fields(self, instance: Any, representation: dict[str, Any], request: Any) -> dict[str, Any]`
482
-
483
- - Core logic to process each file field.
484
- - Converts relative URLs to absolute URLs using `request.build_absolute_uri()`.
485
- - Supports model serializers or manual `file_fields`.
486
- - Logs warnings if request context is missing or file is not found.
487
-
488
- #### Exceptions
489
-
490
- - `MissingRequestContext`: Raised if the request object is missing in serializer context and `DEBUG=True`.
491
-
492
- ### Absolute Url File Mixin Example
493
-
494
- ```python
495
- from rest_framework import serializers
496
- from djresttoolkit.serializers.mixins import AbsoluteUrlFileMixin
497
- from myapp.models import Document
498
-
499
- class DocumentSerializer(AbsoluteUrlFileMixin, serializers.ModelSerializer):
500
- class Meta:
501
- model = Document
502
- fields = ["id", "title", "file"]
503
-
504
- # Output will convert `file` field to an absolute URL
505
- serializer = DocumentSerializer(instance, context={"request": request})
506
- data = serializer.data
507
- ```
508
-
509
- #### Notes
510
-
511
- - Works with both Django model serializers and custom serializers.
512
- - Relative file paths are automatically converted to absolute URLs.
513
- - Can manually specify fields via `file_fields` for non-model serializers.
514
-
515
- ### 9. BulkCreateMixin — API Reference
516
-
517
- ```python
518
- from djresttoolkit.serializers.mixins import BulkCreateMixin
519
- ```
520
-
521
- #### `BulkCreateMixin`
522
-
523
- A **DRF serializer mixin** that adds support for:
524
-
525
- - **Single instance creation** with extra context fields
526
- - **Bulk creation** from a list of validated data dictionaries
527
- - **Updating serializer field error messages** with model-specific messages
528
-
529
- #### Bulk Create Mixin Notes
530
-
531
- - `bulk_create()` does **not trigger model signals** or call `.save()` on instances.
532
- - `Meta.model` **must** be defined in the serializer.
533
-
534
- #### Bulk Create Mixin Methods
535
-
536
- #### `create(self, validated_data: dict[str, Any] | list[dict[str, Any]]) -> Model | list[Model]`
537
-
538
- - Creates single or multiple model instances.
539
- - **Parameters:**
540
- - `validated_data`: dict for single instance or list of dicts for bulk creation.
541
-
542
- - **Returns:**
543
- - Single model instance or list of instances.
544
-
545
- - **Raises:**
546
- - `AttributeError` if `Meta.model` is not defined.
547
- - `NotImplementedError` if used with a serializer that does not implement `create()`.
548
-
549
- #### `get_fields(self) -> dict[str, SerializerField]`
550
-
551
- - Extends DRF serializer `get_fields()` to update **error messages** using model field definitions.
552
- - **Returns:**
553
- - Dictionary of serializer fields.
554
-
555
- - **Warning:**
556
- - Logs a warning if a serializer field is not present on the model.
557
-
558
- ### Bulk Create Mixin Example
559
-
560
- ```python
561
- from rest_framework import serializers
562
- from djresttoolkit.serializers.mixins import BulkCreateMixin
563
- from myapp.models import Product
564
-
565
- class ProductSerializer(BulkCreateMixin, serializers.ModelSerializer):
566
- class Meta:
567
- model = Product
568
- fields = ["id", "name", "price"]
569
-
570
- # Single creation
571
- serializer = ProductSerializer(data={"name": "Item1", "price": 10})
572
- serializer.is_valid(raise_exception=True)
573
- product = serializer.save()
574
-
575
- # Bulk creation
576
- serializer = ProductSerializer(
577
- data=[
578
- {"name": "Item2", "price": 20},
579
- {"name": "Item3", "price": 30},
580
- ],
581
- many=True
582
- )
583
- serializer.is_valid(raise_exception=True)
584
- products = serializer.save()
585
- ```
586
-
587
- #### Bulk Create Mixin Features
588
-
589
- - Works seamlessly with DRF `ModelSerializer`.
590
- - Automatically updates field error messages based on Django model definitions.
591
- - Bulk creation is optimized using `model.objects.bulk_create()` for efficiency.
592
-
593
- ### 10. ModelChoiceFieldMixin — API Reference
594
-
595
- ```python
596
- from djresttoolkit.models.mixins import ModelChoiceFieldMixin
597
- ```
598
-
599
- ### `ModelChoiceFieldMixin`
600
-
601
- A **Django model mixin** to retrieve **choice fields** from a model, designed to work seamlessly with Django's `TextChoices`.
602
-
603
- #### Class Attributes in Model Choice Field Mixin
604
-
605
- - `model: type[Model] | None` — The Django model class to inspect. **Must be set.**
606
- - `choice_fields: list[str] | None` — List of model field names that contain choices. **Must be set.**
607
-
608
- #### Model Choice Field Mixin Methods
609
-
610
- - `get_choices() -> dict[str, dict[str, str]]`
611
-
612
- Retrieve the choice fields from the model as a dictionary.
613
-
614
- - **Returns:**
615
-
616
- ```python
617
- {
618
- "field_name": {
619
- "choice_value": "Choice Label",
620
- ...
621
- },
622
- ...
623
- }
624
- ```
625
-
626
- - **Raises:**
627
-
628
- - `AttributeDoesNotExist` — If `model` or `choice_fields` is not set.
629
- - `ChoiceFieldNotFound` — If a field does not exist, has no choices, or has invalid choice format.
630
-
631
- ---
632
-
633
- ### Model Choice Field Mixin Example
634
-
635
- ```python
636
- from django.db import models
637
- from djresttoolkit.serializers.mixins import ModelChoiceFieldMixin
638
-
639
- class Product(models.Model):
640
- class Status(models.TextChoices):
641
- DRAFT = "draft", "Draft"
642
- PUBLISHED = "published", "Published"
643
-
644
- status = models.CharField(max_length=20, choices=Status.choices)
645
- category = models.CharField(max_length=50, choices=[
646
- ("a", "Category A"),
647
- ("b", "Category B"),
648
- ])
649
-
650
- class ProductChoiceMixin(ModelChoiceFieldMixin):
651
- model = Product
652
- choice_fields = ["status", "category"]
653
-
654
- choices = ProductChoiceMixin.get_choices()
655
- print(choices)
656
- # Output:
657
- # {
658
- # "status": {"draft": "Draft", "published": "Published"},
659
- # "category": {"a": "Category A", "b": "Category B"}
660
- # }
661
- ```
662
-
663
- #### Features of Model Choice Field Mixin
664
-
665
- - Safely validates that fields exist and have valid choices.
666
- - Returns a ready-to-use dictionary mapping values to labels.
667
- - Ideal for DRF serializers, forms, and admin customization.
668
-
669
- Here’s a concise **docs entry** for your `ChoiceFieldsAPIView` suitable for `djresttoolkit` documentation:
670
-
671
- ---
672
-
673
- ### 11. ChoiceFieldsAPIView — API Reference
674
-
675
- ```python
676
- from djresttoolkit.views import ChoiceFieldsAPIView
677
- ```
678
-
679
- #### `ChoiceFieldsAPIView`
680
-
681
- A **generic DRF API view** to return all choices for specified model fields.
682
-
683
- #### Class Attributes of Choice Fields APIView
684
-
685
- - `model_class: type[Model] | None` — The Django model to inspect. **Must be set.**
686
- - `choice_fields: list[str] | None` — List of fields on the model with choices. **Must be set.**
687
-
688
- ---
689
-
690
- #### Choice Fields APIView Methods
691
-
692
- - `get(request: Request) -> Response`
693
-
694
- Fetches the choices for the configured model fields.
695
-
696
- - **Returns:**
697
- - `200 OK` — JSON object containing all choices:
698
-
699
- ```json
700
- {
701
- "choices": {
702
- "status": {"draft": "Draft", "published": "Published"},
703
- "category": {"a": "Category A", "b": "Category B"}
704
- }
705
- }
706
- ```
707
-
708
- - `400 Bad Request` — If any error occurs while retrieving choices.
709
-
710
- - **Raises:**
711
- - `AttributeDoesNotExist` — If `model_class` or `choice_fields` is not set.
712
-
713
- ---
714
-
715
- ### Example of Choice Fields APIView
716
-
717
- ```python
718
- from django.urls import path
719
- from djresttoolkit.views import ChoiceFieldsAPIView
720
- from myapp.models import Product
721
-
722
- class ProductChoiceAPI(ChoiceFieldsAPIView):
723
- model_class = Product
724
- choice_fields = ["status", "category"]
725
-
726
- urlpatterns = [
727
- path(
728
- "api/v1/product-choices/",
729
- ProductChoiceAPI.as_view(),
730
- name="product-choices"
731
- ),
732
- ]
733
- ```
734
-
735
- #### Choice Fields APIView Features
736
-
737
- - Dynamically returns all choices for selected fields in a model.
738
- - Useful for frontend forms or API consumers that need selectable options.
739
- - Integrates seamlessly with `ModelChoiceFieldMixin` from `djresttoolkit`.
740
-
741
- ### 12. RetrieveObjectMixin — API Reference
742
-
743
- ```python
744
- from djresttoolkit.views.mixins import RetrieveObjectMixin
745
- ```
746
-
747
- #### `RetrieveObjectMixin[T: Model]`
748
-
749
- A **generic mixin** to retrieve a single Django model instance by filters.
750
-
751
- #### Class Attributes of Retrieve Object Mixin
752
-
753
- - `queryset: QuerySet[T] | None` — The queryset used to retrieve objects. **Must be set.**
754
-
755
- #### Raises of Retrieve Object Mixin
756
-
757
- - `QuerysetNotDefinedError` — If `queryset` is not set in the class.
758
-
759
- #### Retrieve Object Mixin Methods
760
-
761
- - `get_object(**filters: Any) -> T | None`
762
-
763
- Retrieve a single model object using the provided filter criteria.
764
-
765
- - **Parameters:**
766
- - `**filters` — Keyword arguments to filter the queryset (e.g., `id=1`, `slug="abc"`).
767
-
768
- - **Returns:**
769
- - Model instance matching the filters, or `None` if no match is found.
770
-
771
- #### Example of Retrieve Object Mixin
772
-
773
- ```python
774
- from rest_framework.views import APIView
775
- from django.http import JsonResponse
776
- from myapp.models import Book
777
- from djresttoolkit.mixins import RetrieveObjectMixin
778
-
779
- class BookDetailView(RetrieveObjectMixin[Book], APIView):
780
- queryset = Book.objects.all()
781
-
782
- def get(self, request, *args, **kwargs):
783
- book = self.get_object(id=kwargs["id"])
784
- if book:
785
- return JsonResponse({"title": book.title, "author": book.author})
786
- return JsonResponse({"detail": "Not found"}, status=404)
787
- ```
788
-
789
- #### Features of Retrieve Object Mixin
790
-
791
- - Simplifies object retrieval in class-based views or DRF views.
792
- - Returns `None` instead of raising `DoesNotExist`, making error handling easier.
793
- - Works with any Django model and queryset.
794
-
795
- ### 13. build_absolute_uri — API Reference
796
-
797
- ```python
798
- from djresttoolkit.urls import build_absolute_uri
799
- ```
800
-
801
- #### build absolute uri Description
802
-
803
- - Builds a **fully qualified absolute URL** for a Django or DRF view.
804
- - Optionally includes **query parameters**.
805
- - Works with both **Django `HttpRequest`** and **DRF `Request`** objects.
806
- - Uses Django's `reverse()` to dynamically resolve URL names.
807
-
808
- #### build absolute uri Function Signature
809
-
810
- ```python
811
- def build_absolute_uri(
812
- request: HttpRequest | Request,
813
- url_name: str,
814
- query_params: dict[str, Any] | None = None,
815
- *args: Any,
816
- **kwargs: Any,
817
- ) -> str:
818
- ...
819
- ```
820
-
821
- ---
822
-
823
- #### build absolute uri Parameters
824
-
825
- - `request` (`HttpRequest | Request`): The incoming Django or DRF request object.
826
- - `url_name` (`str`): Name of the URL pattern to reverse.
827
- - `query_params` (`dict[str, Any] | None`): Optional dictionary of query parameters to append to the URL.
828
- - `*args` (`Any`): Positional arguments for the URL reversal.
829
- - `**kwargs` (`Any`): Keyword arguments for the URL reversal.
830
-
831
- ---
832
-
833
- ### build absolute uri Returns
834
-
835
- - `str`: Absolute URI of the view including optional query parameters.
836
-
837
- ### Example of build absolute uri
838
-
839
- ```python
840
- from django.http import HttpRequest
841
- from djresttoolkit.utils import build_absolute_uri
842
-
843
- def my_view(request: HttpRequest):
844
- absolute_url = build_absolute_uri(
845
- request,
846
- url_name="book-detail",
847
- query_params={"ref": "newsletter"},
848
- pk=123
849
- )
850
- return HttpResponse(f"URL: {absolute_url}")
851
- ```
852
-
853
- **Output Example:**
854
-
855
- ```url
856
- https://example.com/api/books/123/?ref=newsletter
857
- ```
858
-
859
- ### 14. PageNumberPagination — API Reference
860
-
861
- ```python
862
- from djresttoolkit.pagination import PageNumberPagination
863
- ```
864
-
865
- #### Description of Page Number Pagination
866
-
867
- - Extends **DRF’s `PageNumberPagination`** with a **cleaner metadata structure**.
868
- - Adds support for **dynamic page size** via the `page-size` query parameter.
869
- - Returns pagination metadata inside a `"page"` object, separate from `"results"`.
870
-
871
- #### Features of Page Number Pagination
872
-
873
- - Clients can control items per page using `?page-size=`.
874
- - Structured pagination metadata:
875
-
876
- - `current`:- current page number
877
- - `total`:- total number of pages
878
- - `size`:- number of items per page
879
- - `total_items`:- total number of items across all pages
880
- - `next`:- next page URL
881
- - `previous`:- previous page URL
882
- - Standardized API response format.
883
-
884
- ### Attributes of Page Number Pagination
885
-
886
- - `page_size_query_param: str`:- Query parameter name (`"page-size"`).
887
-
888
- ### Page Number Pagination Methods
889
-
890
- - `get_paginated_response(data: Any) -> Response`
891
- Returns a JSON response with both pagination metadata and results.
892
-
893
- ### Example Response of Page Number Pagination
894
-
895
- ```json
896
- {
897
- "page": {
898
- "current": 1,
899
- "total": 10,
900
- "size": 20,
901
- "total_items": 200,
902
- "next": "http://api.example.com/items/?page=2&page-size=20",
903
- "previous": null
904
- },
905
- "results": [
906
- { "id": 1, "name": "Item 1" },
907
- { "id": 2, "name": "Item 2" }
908
- ]
909
- }
910
- ```
911
-
912
- ### 15. PaginatedDataBuilder — API Reference
913
-
914
- ```python
915
- from djresttoolkit.pagination import PaginatedDataBuilder
916
- ```
917
-
918
- ---
919
-
920
- #### Description of Paginated Data Builder
921
-
922
- - A **builder utility** to paginate and serialize Django QuerySets using DRF.
923
- - Uses the custom **`PageNumberPagination`** class for consistent pagination responses.
924
- - Designed for reusability inside DRF views and APIs.
925
-
926
- #### Features of Paginated Data Builder
927
-
928
- - Integrates with **DRF serializers**.
929
- - Handles **invalid pages** gracefully by raising `NotFound`.
930
- - Returns both:
931
- - `"page"`:- pagination metadata
932
- - `"results"`:- serialized data.
933
- - Provides **structured pagination response format**.
934
-
935
- ---
936
-
937
- #### Initialization of Paginated Data Builder
938
-
939
- ```python
940
- builder = PaginatedDataBuilder(
941
- request=request,
942
- serializer_class=MySerializer,
943
- queryset=MyModel.objects.all()
944
- )
945
- ```
946
-
947
- - `request: Request`:- DRF request object.
948
- - `serializer_class: type[BaseSerializer]`:- DRF serializer class for the model.
949
- - `queryset: QuerySet`:- Django queryset to paginate.
950
-
951
- ### Paginated Data Builder Methods
952
-
953
- - `get_paginated_data() -> dict[str, Any]`
954
-
955
- - Applies pagination to the queryset.
956
- - Serializes the paginated results.
957
- - Returns a dictionary with `"page"` and `"results"`.
958
- - Raises `NotFound` if no page data is found.
959
-
960
- ### Example Response of Paginated Data Builder
961
-
962
- ```json
963
- {
964
- "page": {
965
- "current": 2,
966
- "total": 5,
967
- "size": 20,
968
- "total_items": 100,
969
- "next": "http://api.example.com/items/?page=3&page-size=20",
970
- "previous": "http://api.example.com/items/?page=1&page-size=20"
971
- },
972
- "results": [
973
- { "id": 21, "name": "Item 21" },
974
- { "id": 22, "name": "Item 22" }
975
- ]
976
- }
977
- ```
978
-
979
- ### 16. Caching Mixins — API Reference
980
-
981
- This module provides a set of DRF mixins to handle **caching for list, retrieve, and custom actions** with automatic invalidation on create, update, and destroy.
982
-
983
- #### 1️ `CacheKeyMixin`
984
-
985
- - **Purpose**: Generate unique cache keys for DRF viewset actions.
986
- - **Attributes**:
987
- - `cache_timeout: int = 300`:- default cache duration in seconds.
988
- - **Methods**:
989
- - `get_cache_timeout()`:- returns the cache timeout.
990
- - `get_cache_key(action_type, pk=None, action_name=None)`:- returns a cache key string based on action type:**
991
- - `list` or `custom-list`:- hash of query parameters.
992
- - `retrieve` or `custom-detail`:- uses primary key (`pk`).
993
-
994
- #### 2️ `CacheOpsMixin`
995
-
996
- - **Purpose**: Get, set, and invalidate cache.
997
- - **Methods**:
998
- - `get_or_set_cache(cache_key, data_fn, timeout=None)`:- fetch from cache or compute and set.
999
- - `invalidate_cache(pk=None, custom_actions=None)`:- delete cached items:
1000
- - Deletes retrieve/detail caches for a `pk`.
1001
- - Deletes list caches (supports `delete_pattern` if available).
1002
-
1003
- #### 3️ `CacheActionMixin`
1004
-
1005
- - **Purpose**: Decorator for caching custom DRF `@action` methods.
1006
- - **Methods**:
1007
- - `cache_action(detail=False, action_name=None)`:- returns a decorator that caches action results automatically.
1008
- - Works for:
1009
- - `detail=False`:- custom-list action cache.
1010
- - `detail=True`:- custom-detail action cache.
1011
-
1012
- #### 4️ `CacheListRetrieveMixin`
1013
-
1014
- - **Purpose**: Caches DRF `list()` and `retrieve()` responses.
1015
- - **Methods**:
1016
- - `list(request, *args, **kwargs)`:- caches list responses.
1017
- - `retrieve(request, *args, **kwargs)`:- caches detail responses.
1018
- - `_get_list_data(request)`:- internal method to fetch paginated list data.
1019
- - `_get_detail_data()`:- internal method to fetch a single object.
1020
-
1021
- #### 5️ `CacheInvalidateMixin`
1022
-
1023
- - **Purpose**: Automatically invalidates caches on write operations.
1024
- - **Methods**:
1025
- - `create(request, *args, **kwargs)`:- invalidates list caches.
1026
- - `update(request, *args, **kwargs)`:- invalidates detail caches for `pk`.
1027
- - `destroy(request, *args, **kwargs)`:- invalidates detail caches for `pk`.
1028
-
1029
- #### Example of Caching Mixins
1030
-
1031
- ```python
1032
- from rest_framework.viewsets import ModelViewSet
1033
- from myapp.models import Book
1034
- from myapp.serializers import BookSerializer
1035
- from djresttoolkit.cache_mixins import CacheInvalidateMixin, CacheActionMixin
1036
-
1037
- class BookViewSet(CacheInvalidateMixin, ModelViewSet):
1038
- queryset = Book.objects.all()
1039
- serializer_class = BookSerializer
1040
- basename = "book"
1041
-
1042
- @CacheActionMixin.cache_action(detail=False)
1043
- def popular(self, request):
1044
- data = Book.objects.filter(is_popular=True)
1045
- serializer = self.get_serializer(data, many=True)
1046
- return Response(serializer.data)
1047
- ```
1048
-
1049
- - Automatically caches `list`, `retrieve`, and `popular` actions.
1050
- - Invalidates caches when books are created, updated, or deleted.
1051
- - Supports custom cache keys per action.
1052
-
1053
- ## 🛠️ Planned Features
1054
-
1055
- - Add more utils
1056
-
1057
- ## 🤝 Contributing
1058
-
1059
- Contributions are welcome! Please open an issue or PR for any improvements.
1060
-
1061
- ## 📜 License
1062
-
1063
- MIT License — See [LICENSE](LICENSE).
1064
-
1065
- ## 👤 Author
1066
-
1067
- For questions or assistance, contact **Shailesh** at [shaileshpandit141@gmail.com](mailto:shaileshpandit141@gmail.com).