drf-fast-output 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.
- drf_fast_output-0.1.0/LICENSE +21 -0
- drf_fast_output-0.1.0/PKG-INFO +283 -0
- drf_fast_output-0.1.0/README.md +247 -0
- drf_fast_output-0.1.0/drf_fast_output/__init__.py +61 -0
- drf_fast_output-0.1.0/drf_fast_output/compiler.py +831 -0
- drf_fast_output-0.1.0/drf_fast_output/conf.py +48 -0
- drf_fast_output-0.1.0/drf_fast_output/py.typed +0 -0
- drf_fast_output-0.1.0/drf_fast_output/serializers.py +211 -0
- drf_fast_output-0.1.0/drf_fast_output/views.py +36 -0
- drf_fast_output-0.1.0/pyproject.toml +112 -0
- drf_fast_output-0.1.0/pyproject.toml.orig +103 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Marco Peyfuss
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: drf-fast-output
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Faster output serialization for Django REST Framework read endpoints
|
|
5
|
+
Keywords: django,djangorestframework,drf,serializer,performance
|
|
6
|
+
Author: Marco Peyfuss
|
|
7
|
+
Author-email: Marco Peyfuss <82735893+mpeyfuss@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Framework :: Django
|
|
12
|
+
Classifier: Framework :: Django :: 4.2
|
|
13
|
+
Classifier: Framework :: Django :: 5.0
|
|
14
|
+
Classifier: Framework :: Django :: 5.1
|
|
15
|
+
Classifier: Framework :: Django :: 5.2
|
|
16
|
+
Classifier: Framework :: Django :: 6.0
|
|
17
|
+
Classifier: Framework :: Django :: 6.1
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Classifier: Operating System :: OS Independent
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
27
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
28
|
+
Classifier: Typing :: Typed
|
|
29
|
+
Requires-Dist: django>=4.2
|
|
30
|
+
Requires-Dist: djangorestframework>=3.15
|
|
31
|
+
Requires-Python: >=3.10
|
|
32
|
+
Project-URL: Homepage, https://github.com/mpeyfuss/drf-fast-output
|
|
33
|
+
Project-URL: Repository, https://github.com/mpeyfuss/drf-fast-output
|
|
34
|
+
Project-URL: Issues, https://github.com/mpeyfuss/drf-fast-output/issues
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# drf-fast-output
|
|
38
|
+
|
|
39
|
+
Faster output serialization for Django REST Framework read endpoints, with the
|
|
40
|
+
same output as stock DRF.
|
|
41
|
+
|
|
42
|
+
DRF's `Serializer.to_representation` does a lot of generic work for every field
|
|
43
|
+
of every row: `field.get_attribute()` → `fields.get_attribute()` → `getattr`, a
|
|
44
|
+
`PKOnlyObject` check, a method call to `field.to_representation()`, and for
|
|
45
|
+
method sources (`source="get_status_display"`) an `inspect.signature()` call per
|
|
46
|
+
row. This package compiles each serializer into one generated Python function
|
|
47
|
+
that does the same thing with that work inlined.
|
|
48
|
+
|
|
49
|
+
Serialization time only (`benchmarks/bench.py`, Python 3.15, Django 6.1), the
|
|
50
|
+
same serializer as plain DRF classes vs fast:
|
|
51
|
+
|
|
52
|
+
| case | 1 row | 5 rows | 25 rows | 2000 rows |
|
|
53
|
+
|---|---|---|---|---|
|
|
54
|
+
| `ModelSerializer`, `fields='__all__'` | 0.91x | 1.37x | 2.61x | 5.9x |
|
|
55
|
+
| Nested (FK, O2O, reverse FK, M2M, method fields) | 0.91x | 1.30x | 2.45x | 3.9x |
|
|
56
|
+
| `fast_output()` on a stock serializer | 0.83x | 1.07x | 1.95x | 5.5x |
|
|
57
|
+
|
|
58
|
+
The small-row numbers include constructing the serializer. A single object is
|
|
59
|
+
somewhat slower (up to ~17%), and everything from a handful of rows up gets
|
|
60
|
+
faster. Compiled plans are shared by every serializer instance with the
|
|
61
|
+
same field configuration, so each request only pays for binding its own field
|
|
62
|
+
objects.
|
|
63
|
+
|
|
64
|
+
## Usage
|
|
65
|
+
|
|
66
|
+
The options below all give the same result. Pick whichever fits your code.
|
|
67
|
+
|
|
68
|
+
**1. Per serializer**: mix it in before the DRF base class, or use the ready-made bases:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from drf_fast_output import FastOutputMixin, FastModelSerializer
|
|
72
|
+
|
|
73
|
+
class BookSerializer(FastOutputMixin, serializers.ModelSerializer):
|
|
74
|
+
...
|
|
75
|
+
|
|
76
|
+
class AuthorSerializer(FastModelSerializer): # same thing
|
|
77
|
+
...
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
**2. Per view, read requests only**: leave your serializers untouched:
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from drf_fast_output.views import FastOutputViewMixin
|
|
84
|
+
|
|
85
|
+
class BookViewSet(FastOutputViewMixin, viewsets.ModelViewSet):
|
|
86
|
+
serializer_class = BookSerializer # GET/HEAD/OPTIONS get the fast version
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
**3. Wrap a class**:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from drf_fast_output import fast_output
|
|
93
|
+
|
|
94
|
+
class BookList(generics.ListAPIView):
|
|
95
|
+
serializer_class = fast_output(BookSerializer) # cached subclass, same name/Meta
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Nested serializers are compiled into the parent automatically, even plain DRF
|
|
99
|
+
ones. Only output changes. Validation, `is_valid()` and `save()` are stock DRF.
|
|
100
|
+
|
|
101
|
+
### Write endpoints
|
|
102
|
+
|
|
103
|
+
Fast serializers work on write endpoints. `is_valid()`, `create()`, `update()`
|
|
104
|
+
and `save()` are untouched, and the response after `save()` goes through the
|
|
105
|
+
fast path. The view mixin only switches serializers for reads by default. To
|
|
106
|
+
include write responses, set `fast_output_methods`:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
class BookViewSet(FastOutputViewMixin, viewsets.ModelViewSet):
|
|
110
|
+
fast_output_methods = ("GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH")
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
A write response is usually a single object, so expect break-even rather than
|
|
114
|
+
a speedup.
|
|
115
|
+
|
|
116
|
+
### Renderers
|
|
117
|
+
|
|
118
|
+
The output is the same Python objects stock DRF produces, so any renderer
|
|
119
|
+
gives the same bytes it would without this package. That includes DRF's
|
|
120
|
+
`JSONRenderer`, [drf-orjson-renderer](https://github.com/brianjbuck/drf_orjson_renderer),
|
|
121
|
+
and XML or YAML renderers. The two speedups combine: on the nested benchmark
|
|
122
|
+
above, `JSONRenderer` takes 7.2 ms to render what this package serializes in
|
|
123
|
+
about 50 ms, and `ORJSONRenderer` takes 1.6 ms.
|
|
124
|
+
|
|
125
|
+
## What gets inlined
|
|
126
|
+
|
|
127
|
+
Each readable field gets an **access** strategy and a **conversion**:
|
|
128
|
+
|
|
129
|
+
| access | used for |
|
|
130
|
+
|------------|------------------------------------------------------------------|
|
|
131
|
+
| `attr` | concrete model columns (`o.title`), FK pks (`o.author_id`) |
|
|
132
|
+
| `fkobj` | forward FK/O2O to a nested serializer (`o.author`, missing → `None`) |
|
|
133
|
+
| `prefetch` | to-many relations: reads Django's prefetch cache when populated |
|
|
134
|
+
| `call` | model method sources such as `get_FOO_display` |
|
|
135
|
+
| `method` | `SerializerMethodField` |
|
|
136
|
+
| `get` | everything else: DRF's own `field.get_attribute()` |
|
|
137
|
+
|
|
138
|
+
Conversions are inlined for `CharField` (and Email/Slug/URL/...), `IntegerField`,
|
|
139
|
+
`BigIntegerField`, `FloatField`, `BooleanField`, `ChoiceField`, `UUIDField`,
|
|
140
|
+
`DateField`, `TimeField`, `DateTimeField` (ISO-8601 output in UTC or with
|
|
141
|
+
`USE_TZ=False`), `JSONField`, `ReadOnlyField`, `PrimaryKeyRelatedField`, many-pk
|
|
142
|
+
fields, and nested serializers / `many=True`. Anything else, such as `DecimalField`,
|
|
143
|
+
custom fields, or non-ISO formats, calls the field's own `to_representation`.
|
|
144
|
+
|
|
145
|
+
### Correctness rules
|
|
146
|
+
|
|
147
|
+
- A shortcut is only taken when the field class has **not** overridden the DRF
|
|
148
|
+
method it replaces. A `CharField` subclass with its own `to_representation`
|
|
149
|
+
still gets fast attribute access, but its conversion is its own.
|
|
150
|
+
- Serializers that override `to_representation` are honoured. Nested ones are
|
|
151
|
+
called as-is, and top-level ones still get the fast path when they call `super()`.
|
|
152
|
+
- Inline conversions are guarded by exact type checks (`type(v) is str`),
|
|
153
|
+
and other values go to the field. For example, a `TextChoices` member or a
|
|
154
|
+
`SimpleLazyObject` goes through the field's `to_representation`.
|
|
155
|
+
- Instances that are not of `Meta.model` (dicts, other objects) take DRF's
|
|
156
|
+
path for that row.
|
|
157
|
+
- Relations that weren't prefetched, or were prefetched with `to_attr`, take DRF's
|
|
158
|
+
path. The fast path never issues more queries than DRF.
|
|
159
|
+
- Custom `list_serializer_class` is left alone. Its children are still fast.
|
|
160
|
+
|
|
161
|
+
## When not to use it
|
|
162
|
+
|
|
163
|
+
The output is always correct, but there are cases where it doesn't help, or
|
|
164
|
+
where its assumptions don't hold.
|
|
165
|
+
|
|
166
|
+
**It won't be faster:**
|
|
167
|
+
|
|
168
|
+
- **Single-object endpoints** (detail views, write responses) are a little slower,
|
|
169
|
+
at 0.83–0.91x of stock DRF in the benchmark. The gains need several rows, or nested lists
|
|
170
|
+
inside the object (a detail view with 200 nested rows measured 1.5x). One
|
|
171
|
+
edge case is a single object rendered through several small nested
|
|
172
|
+
serializers. Each one is compiled for that request, and the setup can cost
|
|
173
|
+
more than it saves. The worst case measured was about 6% slower. If an
|
|
174
|
+
endpoint like that matters, give it a regular DRF serializer, or set
|
|
175
|
+
`Meta.fast_output = False` on its serializer.
|
|
176
|
+
- **When serialization isn't the bottleneck.** If the endpoint has N+1 queries
|
|
177
|
+
or slow database calls, fix those first. This package doesn't change what
|
|
178
|
+
gets queried.
|
|
179
|
+
- **When most fields fall back to DRF.** Run `explain()`. Fields marked `get`
|
|
180
|
+
or `generic` still go through DRF: `DecimalField`, `DurationField`, dotted
|
|
181
|
+
sources (`author.name`), properties, reverse one-to-one, hyperlinked fields,
|
|
182
|
+
custom fields, non-ISO date formats, and datetimes in a non-UTC timezone when
|
|
183
|
+
`USE_TZ=True`. A serializer made mostly of these gains little.
|
|
184
|
+
- **Slow `SerializerMethodField`s.** If a method does its own queries or heavy
|
|
185
|
+
work, that cost is unchanged.
|
|
186
|
+
|
|
187
|
+
**Avoid these patterns, or test them with `VERIFY` on:**
|
|
188
|
+
|
|
189
|
+
- **Overriding `all()` on a related model's default manager.** For prefetched
|
|
190
|
+
relations the fast path reads Django's prefetch cache directly instead of
|
|
191
|
+
calling `.all()`, so a custom `all()` is skipped. Relations that weren't
|
|
192
|
+
prefetched still call it.
|
|
193
|
+
- **Changing a serializer after its first `.data`.** A serializer compiles on
|
|
194
|
+
first use and keeps the result. Swapping `serializer.fields`, field
|
|
195
|
+
formats or choices, or a `get_<name>` method afterwards isn't picked up.
|
|
196
|
+
Changes made in `__init__` are fine.
|
|
197
|
+
- **Model subclasses that override `serializable_value()`.** Only `Meta.model`
|
|
198
|
+
itself is checked, not subclass instances.
|
|
199
|
+
- **Code that expects DRF's per-row lookups.** A `SerializerMethodField`'s
|
|
200
|
+
method is looked up once per serializer instead of once per row. A model
|
|
201
|
+
method used as a source (`source="get_summary"`) is checked once up front
|
|
202
|
+
instead of being re-inspected on every row.
|
|
203
|
+
- **Switching timezones while a list is being consumed.** The active timezone
|
|
204
|
+
is read once per `many=True` call, not per row. If the input is a generator
|
|
205
|
+
that yields rows inside different `timezone.override()` blocks, all rows are
|
|
206
|
+
rendered in the timezone that was active when serialization started. Stock
|
|
207
|
+
DRF uses each row's. `VERIFY` catches this.
|
|
208
|
+
|
|
209
|
+
**Other things to know:**
|
|
210
|
+
|
|
211
|
+
- **`VERIFY` runs every serialization twice.** Method fields run twice and
|
|
212
|
+
queries can double, so use it in tests, not production.
|
|
213
|
+
- **Compiled code is cached per field configuration, up to 512 entries.**
|
|
214
|
+
Endpoints whose fields are chosen by the client (sparse fieldsets via
|
|
215
|
+
`?fields=`) can produce many configurations. Past the limit, the oldest
|
|
216
|
+
entries are evicted and recompiled when they come back. That is always
|
|
217
|
+
correct, but an endpoint that cycles through more than 512 combinations
|
|
218
|
+
pays the compile cost again and again. The limit isn't configurable.
|
|
219
|
+
- **Errors raised inside the generated code have hard-to-read tracebacks.**
|
|
220
|
+
Frames show `<drf_fast_output>` without source lines. Set
|
|
221
|
+
`DRF_FAST_OUTPUT = {"ENABLED": False}` to debug through stock DRF.
|
|
222
|
+
- **Mixin order matters.** `FastOutputMixin` must come before the DRF base
|
|
223
|
+
class. The wrong order raises a `TypeError`.
|
|
224
|
+
- **It generates Python code with `exec`.** Only field names, prefetch keys and
|
|
225
|
+
validated identifiers go into the generated source, but environments that
|
|
226
|
+
forbid `exec` can't use it.
|
|
227
|
+
- **It depends on DRF and Django internals:** `_readable_fields`,
|
|
228
|
+
`PKOnlyObject`, `choice_strings_to_values` and `_prefetched_objects_cache`.
|
|
229
|
+
Run your test suite with `VERIFY` on when you upgrade DRF or Django.
|
|
230
|
+
|
|
231
|
+
## Settings
|
|
232
|
+
|
|
233
|
+
```python
|
|
234
|
+
DRF_FAST_OUTPUT = {
|
|
235
|
+
"ENABLED": True, # master switch
|
|
236
|
+
"VERIFY": False, # compute stock DRF output too and raise on any difference
|
|
237
|
+
}
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Turn on **`VERIFY` in your test settings**. Every fast serialization is then
|
|
241
|
+
compared against stock DRF, checking types and key order as well, so `1` vs `True` or a
|
|
242
|
+
reordered dict fails loudly. Lists are compared row by row as they are consumed,
|
|
243
|
+
so generators behave as they do without `VERIFY`.
|
|
244
|
+
|
|
245
|
+
Both settings take effect on the next call, including on serializer instances
|
|
246
|
+
that have already been used.
|
|
247
|
+
|
|
248
|
+
Opt a single serializer out with `Meta.fast_output = False`.
|
|
249
|
+
|
|
250
|
+
## Debugging
|
|
251
|
+
|
|
252
|
+
```python
|
|
253
|
+
>>> from drf_fast_output import explain
|
|
254
|
+
>>> print(explain(BookSerializer(qs, many=True)))
|
|
255
|
+
BookSerializer
|
|
256
|
+
id: access=attr id conv=int
|
|
257
|
+
title: access=attr title conv=str
|
|
258
|
+
author: access=fkobj author conv=nested
|
|
259
|
+
id: access=attr id conv=int
|
|
260
|
+
name: access=attr name conv=str
|
|
261
|
+
tags: access=prefetch tags conv=pklist
|
|
262
|
+
status_display: access=call get_status_display conv=str
|
|
263
|
+
price: access=attr price conv=generic
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
Fields with `get` or `generic` are the ones still going through DRF's machinery.
|
|
267
|
+
|
|
268
|
+
## Development
|
|
269
|
+
|
|
270
|
+
```bash
|
|
271
|
+
uv sync
|
|
272
|
+
uv run pytest
|
|
273
|
+
uv run ruff check && uv run ruff format --check # lint + formatting
|
|
274
|
+
uv run pyrefly check # type check
|
|
275
|
+
uv run python benchmarks/bench.py 2000 # large and small result sets
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
Every test in the suite renders through both paths and asserts identical output
|
|
279
|
+
and no extra queries. It covers Python 3.10–3.15, Django 4.2–6.1 and DRF 3.15–3.18.
|
|
280
|
+
|
|
281
|
+
## License
|
|
282
|
+
|
|
283
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
# drf-fast-output
|
|
2
|
+
|
|
3
|
+
Faster output serialization for Django REST Framework read endpoints, with the
|
|
4
|
+
same output as stock DRF.
|
|
5
|
+
|
|
6
|
+
DRF's `Serializer.to_representation` does a lot of generic work for every field
|
|
7
|
+
of every row: `field.get_attribute()` → `fields.get_attribute()` → `getattr`, a
|
|
8
|
+
`PKOnlyObject` check, a method call to `field.to_representation()`, and for
|
|
9
|
+
method sources (`source="get_status_display"`) an `inspect.signature()` call per
|
|
10
|
+
row. This package compiles each serializer into one generated Python function
|
|
11
|
+
that does the same thing with that work inlined.
|
|
12
|
+
|
|
13
|
+
Serialization time only (`benchmarks/bench.py`, Python 3.15, Django 6.1), the
|
|
14
|
+
same serializer as plain DRF classes vs fast:
|
|
15
|
+
|
|
16
|
+
| case | 1 row | 5 rows | 25 rows | 2000 rows |
|
|
17
|
+
|---|---|---|---|---|
|
|
18
|
+
| `ModelSerializer`, `fields='__all__'` | 0.91x | 1.37x | 2.61x | 5.9x |
|
|
19
|
+
| Nested (FK, O2O, reverse FK, M2M, method fields) | 0.91x | 1.30x | 2.45x | 3.9x |
|
|
20
|
+
| `fast_output()` on a stock serializer | 0.83x | 1.07x | 1.95x | 5.5x |
|
|
21
|
+
|
|
22
|
+
The small-row numbers include constructing the serializer. A single object is
|
|
23
|
+
somewhat slower (up to ~17%), and everything from a handful of rows up gets
|
|
24
|
+
faster. Compiled plans are shared by every serializer instance with the
|
|
25
|
+
same field configuration, so each request only pays for binding its own field
|
|
26
|
+
objects.
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
The options below all give the same result. Pick whichever fits your code.
|
|
31
|
+
|
|
32
|
+
**1. Per serializer**: mix it in before the DRF base class, or use the ready-made bases:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from drf_fast_output import FastOutputMixin, FastModelSerializer
|
|
36
|
+
|
|
37
|
+
class BookSerializer(FastOutputMixin, serializers.ModelSerializer):
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
class AuthorSerializer(FastModelSerializer): # same thing
|
|
41
|
+
...
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
**2. Per view, read requests only**: leave your serializers untouched:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from drf_fast_output.views import FastOutputViewMixin
|
|
48
|
+
|
|
49
|
+
class BookViewSet(FastOutputViewMixin, viewsets.ModelViewSet):
|
|
50
|
+
serializer_class = BookSerializer # GET/HEAD/OPTIONS get the fast version
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
**3. Wrap a class**:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from drf_fast_output import fast_output
|
|
57
|
+
|
|
58
|
+
class BookList(generics.ListAPIView):
|
|
59
|
+
serializer_class = fast_output(BookSerializer) # cached subclass, same name/Meta
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Nested serializers are compiled into the parent automatically, even plain DRF
|
|
63
|
+
ones. Only output changes. Validation, `is_valid()` and `save()` are stock DRF.
|
|
64
|
+
|
|
65
|
+
### Write endpoints
|
|
66
|
+
|
|
67
|
+
Fast serializers work on write endpoints. `is_valid()`, `create()`, `update()`
|
|
68
|
+
and `save()` are untouched, and the response after `save()` goes through the
|
|
69
|
+
fast path. The view mixin only switches serializers for reads by default. To
|
|
70
|
+
include write responses, set `fast_output_methods`:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
class BookViewSet(FastOutputViewMixin, viewsets.ModelViewSet):
|
|
74
|
+
fast_output_methods = ("GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH")
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
A write response is usually a single object, so expect break-even rather than
|
|
78
|
+
a speedup.
|
|
79
|
+
|
|
80
|
+
### Renderers
|
|
81
|
+
|
|
82
|
+
The output is the same Python objects stock DRF produces, so any renderer
|
|
83
|
+
gives the same bytes it would without this package. That includes DRF's
|
|
84
|
+
`JSONRenderer`, [drf-orjson-renderer](https://github.com/brianjbuck/drf_orjson_renderer),
|
|
85
|
+
and XML or YAML renderers. The two speedups combine: on the nested benchmark
|
|
86
|
+
above, `JSONRenderer` takes 7.2 ms to render what this package serializes in
|
|
87
|
+
about 50 ms, and `ORJSONRenderer` takes 1.6 ms.
|
|
88
|
+
|
|
89
|
+
## What gets inlined
|
|
90
|
+
|
|
91
|
+
Each readable field gets an **access** strategy and a **conversion**:
|
|
92
|
+
|
|
93
|
+
| access | used for |
|
|
94
|
+
|------------|------------------------------------------------------------------|
|
|
95
|
+
| `attr` | concrete model columns (`o.title`), FK pks (`o.author_id`) |
|
|
96
|
+
| `fkobj` | forward FK/O2O to a nested serializer (`o.author`, missing → `None`) |
|
|
97
|
+
| `prefetch` | to-many relations: reads Django's prefetch cache when populated |
|
|
98
|
+
| `call` | model method sources such as `get_FOO_display` |
|
|
99
|
+
| `method` | `SerializerMethodField` |
|
|
100
|
+
| `get` | everything else: DRF's own `field.get_attribute()` |
|
|
101
|
+
|
|
102
|
+
Conversions are inlined for `CharField` (and Email/Slug/URL/...), `IntegerField`,
|
|
103
|
+
`BigIntegerField`, `FloatField`, `BooleanField`, `ChoiceField`, `UUIDField`,
|
|
104
|
+
`DateField`, `TimeField`, `DateTimeField` (ISO-8601 output in UTC or with
|
|
105
|
+
`USE_TZ=False`), `JSONField`, `ReadOnlyField`, `PrimaryKeyRelatedField`, many-pk
|
|
106
|
+
fields, and nested serializers / `many=True`. Anything else, such as `DecimalField`,
|
|
107
|
+
custom fields, or non-ISO formats, calls the field's own `to_representation`.
|
|
108
|
+
|
|
109
|
+
### Correctness rules
|
|
110
|
+
|
|
111
|
+
- A shortcut is only taken when the field class has **not** overridden the DRF
|
|
112
|
+
method it replaces. A `CharField` subclass with its own `to_representation`
|
|
113
|
+
still gets fast attribute access, but its conversion is its own.
|
|
114
|
+
- Serializers that override `to_representation` are honoured. Nested ones are
|
|
115
|
+
called as-is, and top-level ones still get the fast path when they call `super()`.
|
|
116
|
+
- Inline conversions are guarded by exact type checks (`type(v) is str`),
|
|
117
|
+
and other values go to the field. For example, a `TextChoices` member or a
|
|
118
|
+
`SimpleLazyObject` goes through the field's `to_representation`.
|
|
119
|
+
- Instances that are not of `Meta.model` (dicts, other objects) take DRF's
|
|
120
|
+
path for that row.
|
|
121
|
+
- Relations that weren't prefetched, or were prefetched with `to_attr`, take DRF's
|
|
122
|
+
path. The fast path never issues more queries than DRF.
|
|
123
|
+
- Custom `list_serializer_class` is left alone. Its children are still fast.
|
|
124
|
+
|
|
125
|
+
## When not to use it
|
|
126
|
+
|
|
127
|
+
The output is always correct, but there are cases where it doesn't help, or
|
|
128
|
+
where its assumptions don't hold.
|
|
129
|
+
|
|
130
|
+
**It won't be faster:**
|
|
131
|
+
|
|
132
|
+
- **Single-object endpoints** (detail views, write responses) are a little slower,
|
|
133
|
+
at 0.83–0.91x of stock DRF in the benchmark. The gains need several rows, or nested lists
|
|
134
|
+
inside the object (a detail view with 200 nested rows measured 1.5x). One
|
|
135
|
+
edge case is a single object rendered through several small nested
|
|
136
|
+
serializers. Each one is compiled for that request, and the setup can cost
|
|
137
|
+
more than it saves. The worst case measured was about 6% slower. If an
|
|
138
|
+
endpoint like that matters, give it a regular DRF serializer, or set
|
|
139
|
+
`Meta.fast_output = False` on its serializer.
|
|
140
|
+
- **When serialization isn't the bottleneck.** If the endpoint has N+1 queries
|
|
141
|
+
or slow database calls, fix those first. This package doesn't change what
|
|
142
|
+
gets queried.
|
|
143
|
+
- **When most fields fall back to DRF.** Run `explain()`. Fields marked `get`
|
|
144
|
+
or `generic` still go through DRF: `DecimalField`, `DurationField`, dotted
|
|
145
|
+
sources (`author.name`), properties, reverse one-to-one, hyperlinked fields,
|
|
146
|
+
custom fields, non-ISO date formats, and datetimes in a non-UTC timezone when
|
|
147
|
+
`USE_TZ=True`. A serializer made mostly of these gains little.
|
|
148
|
+
- **Slow `SerializerMethodField`s.** If a method does its own queries or heavy
|
|
149
|
+
work, that cost is unchanged.
|
|
150
|
+
|
|
151
|
+
**Avoid these patterns, or test them with `VERIFY` on:**
|
|
152
|
+
|
|
153
|
+
- **Overriding `all()` on a related model's default manager.** For prefetched
|
|
154
|
+
relations the fast path reads Django's prefetch cache directly instead of
|
|
155
|
+
calling `.all()`, so a custom `all()` is skipped. Relations that weren't
|
|
156
|
+
prefetched still call it.
|
|
157
|
+
- **Changing a serializer after its first `.data`.** A serializer compiles on
|
|
158
|
+
first use and keeps the result. Swapping `serializer.fields`, field
|
|
159
|
+
formats or choices, or a `get_<name>` method afterwards isn't picked up.
|
|
160
|
+
Changes made in `__init__` are fine.
|
|
161
|
+
- **Model subclasses that override `serializable_value()`.** Only `Meta.model`
|
|
162
|
+
itself is checked, not subclass instances.
|
|
163
|
+
- **Code that expects DRF's per-row lookups.** A `SerializerMethodField`'s
|
|
164
|
+
method is looked up once per serializer instead of once per row. A model
|
|
165
|
+
method used as a source (`source="get_summary"`) is checked once up front
|
|
166
|
+
instead of being re-inspected on every row.
|
|
167
|
+
- **Switching timezones while a list is being consumed.** The active timezone
|
|
168
|
+
is read once per `many=True` call, not per row. If the input is a generator
|
|
169
|
+
that yields rows inside different `timezone.override()` blocks, all rows are
|
|
170
|
+
rendered in the timezone that was active when serialization started. Stock
|
|
171
|
+
DRF uses each row's. `VERIFY` catches this.
|
|
172
|
+
|
|
173
|
+
**Other things to know:**
|
|
174
|
+
|
|
175
|
+
- **`VERIFY` runs every serialization twice.** Method fields run twice and
|
|
176
|
+
queries can double, so use it in tests, not production.
|
|
177
|
+
- **Compiled code is cached per field configuration, up to 512 entries.**
|
|
178
|
+
Endpoints whose fields are chosen by the client (sparse fieldsets via
|
|
179
|
+
`?fields=`) can produce many configurations. Past the limit, the oldest
|
|
180
|
+
entries are evicted and recompiled when they come back. That is always
|
|
181
|
+
correct, but an endpoint that cycles through more than 512 combinations
|
|
182
|
+
pays the compile cost again and again. The limit isn't configurable.
|
|
183
|
+
- **Errors raised inside the generated code have hard-to-read tracebacks.**
|
|
184
|
+
Frames show `<drf_fast_output>` without source lines. Set
|
|
185
|
+
`DRF_FAST_OUTPUT = {"ENABLED": False}` to debug through stock DRF.
|
|
186
|
+
- **Mixin order matters.** `FastOutputMixin` must come before the DRF base
|
|
187
|
+
class. The wrong order raises a `TypeError`.
|
|
188
|
+
- **It generates Python code with `exec`.** Only field names, prefetch keys and
|
|
189
|
+
validated identifiers go into the generated source, but environments that
|
|
190
|
+
forbid `exec` can't use it.
|
|
191
|
+
- **It depends on DRF and Django internals:** `_readable_fields`,
|
|
192
|
+
`PKOnlyObject`, `choice_strings_to_values` and `_prefetched_objects_cache`.
|
|
193
|
+
Run your test suite with `VERIFY` on when you upgrade DRF or Django.
|
|
194
|
+
|
|
195
|
+
## Settings
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
DRF_FAST_OUTPUT = {
|
|
199
|
+
"ENABLED": True, # master switch
|
|
200
|
+
"VERIFY": False, # compute stock DRF output too and raise on any difference
|
|
201
|
+
}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Turn on **`VERIFY` in your test settings**. Every fast serialization is then
|
|
205
|
+
compared against stock DRF, checking types and key order as well, so `1` vs `True` or a
|
|
206
|
+
reordered dict fails loudly. Lists are compared row by row as they are consumed,
|
|
207
|
+
so generators behave as they do without `VERIFY`.
|
|
208
|
+
|
|
209
|
+
Both settings take effect on the next call, including on serializer instances
|
|
210
|
+
that have already been used.
|
|
211
|
+
|
|
212
|
+
Opt a single serializer out with `Meta.fast_output = False`.
|
|
213
|
+
|
|
214
|
+
## Debugging
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
>>> from drf_fast_output import explain
|
|
218
|
+
>>> print(explain(BookSerializer(qs, many=True)))
|
|
219
|
+
BookSerializer
|
|
220
|
+
id: access=attr id conv=int
|
|
221
|
+
title: access=attr title conv=str
|
|
222
|
+
author: access=fkobj author conv=nested
|
|
223
|
+
id: access=attr id conv=int
|
|
224
|
+
name: access=attr name conv=str
|
|
225
|
+
tags: access=prefetch tags conv=pklist
|
|
226
|
+
status_display: access=call get_status_display conv=str
|
|
227
|
+
price: access=attr price conv=generic
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
Fields with `get` or `generic` are the ones still going through DRF's machinery.
|
|
231
|
+
|
|
232
|
+
## Development
|
|
233
|
+
|
|
234
|
+
```bash
|
|
235
|
+
uv sync
|
|
236
|
+
uv run pytest
|
|
237
|
+
uv run ruff check && uv run ruff format --check # lint + formatting
|
|
238
|
+
uv run pyrefly check # type check
|
|
239
|
+
uv run python benchmarks/bench.py 2000 # large and small result sets
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Every test in the suite renders through both paths and asserts identical output
|
|
243
|
+
and no extra queries. It covers Python 3.10–3.15, Django 4.2–6.1 and DRF 3.15–3.18.
|
|
244
|
+
|
|
245
|
+
## License
|
|
246
|
+
|
|
247
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Faster output serialization for Django REST Framework read paths."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .serializers import (
|
|
8
|
+
FastListSerializer,
|
|
9
|
+
FastModelSerializer,
|
|
10
|
+
FastOutputMixin,
|
|
11
|
+
FastSerializer,
|
|
12
|
+
fast_output,
|
|
13
|
+
strict_equal,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"FastListSerializer",
|
|
18
|
+
"FastModelSerializer",
|
|
19
|
+
"FastOutputMixin",
|
|
20
|
+
"FastSerializer",
|
|
21
|
+
"explain",
|
|
22
|
+
"fast_output",
|
|
23
|
+
"strict_equal",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def explain(serializer: Any) -> str:
|
|
28
|
+
"""
|
|
29
|
+
Human-readable per-field plan for a serializer instance: how each field is
|
|
30
|
+
read and converted. Fields on ``get`` / ``generic`` go through DRF itself.
|
|
31
|
+
"""
|
|
32
|
+
from . import compiler
|
|
33
|
+
|
|
34
|
+
# Mirrors the entry points' checks, including methods assigned on the
|
|
35
|
+
# instance (.data then calls those, not the compiled row).
|
|
36
|
+
usable = compiler.enabled()
|
|
37
|
+
if hasattr(serializer, "child"): # many=True
|
|
38
|
+
if isinstance(serializer, FastListSerializer):
|
|
39
|
+
usable = usable and serializer._fast_output_ok
|
|
40
|
+
usable = usable and "to_representation" not in serializer.__dict__
|
|
41
|
+
serializer = serializer.child
|
|
42
|
+
usable = usable and "to_representation" not in serializer.__dict__
|
|
43
|
+
lines: list[str] = [type(serializer).__qualname__]
|
|
44
|
+
|
|
45
|
+
def walk(ser: Any, indent: str) -> None:
|
|
46
|
+
# Nested/list conversions are only planned for inlineable serializers.
|
|
47
|
+
for p in compiler.plan(ser):
|
|
48
|
+
target = f" {p.attr}" if p.attr else ""
|
|
49
|
+
lines.append(f"{indent}{p.key}: access={p.access}{target} conv={p.conv}")
|
|
50
|
+
if p.conv in ("nested", "list"):
|
|
51
|
+
walk(getattr(p.field, "child", p.field), indent + " ")
|
|
52
|
+
|
|
53
|
+
if isinstance(serializer, FastOutputMixin):
|
|
54
|
+
usable = usable and serializer._fast_output_row is not None
|
|
55
|
+
else:
|
|
56
|
+
usable = usable and compiler.inlineable(serializer)
|
|
57
|
+
if usable:
|
|
58
|
+
walk(serializer, " ")
|
|
59
|
+
else:
|
|
60
|
+
lines.append(" (not inlined: custom to_representation or opted out)")
|
|
61
|
+
return "\n".join(lines)
|