django-redline 0.2.0a1__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.
- django_redline-0.2.0a1/.gitignore +21 -0
- django_redline-0.2.0a1/LICENSE +21 -0
- django_redline-0.2.0a1/PKG-INFO +229 -0
- django_redline-0.2.0a1/README.md +192 -0
- django_redline-0.2.0a1/pyproject.toml +90 -0
- django_redline-0.2.0a1/src/django_redline/__init__.py +23 -0
- django_redline-0.2.0a1/src/django_redline/_drf.py +82 -0
- django_redline-0.2.0a1/src/django_redline/apps.py +30 -0
- django_redline-0.2.0a1/src/django_redline/checks.py +142 -0
- django_redline-0.2.0a1/src/django_redline/conf.py +182 -0
- django_redline-0.2.0a1/src/django_redline/explain.py +52 -0
- django_redline-0.2.0a1/src/django_redline/instrument.py +557 -0
- django_redline-0.2.0a1/src/django_redline/management/__init__.py +0 -0
- django_redline-0.2.0a1/src/django_redline/management/commands/__init__.py +0 -0
- django_redline-0.2.0a1/src/django_redline/management/commands/redline_clear.py +31 -0
- django_redline-0.2.0a1/src/django_redline/management/commands/redline_prune.py +38 -0
- django_redline-0.2.0a1/src/django_redline/management/commands/redline_scan.py +58 -0
- django_redline-0.2.0a1/src/django_redline/management/commands/redline_scenario.py +135 -0
- django_redline-0.2.0a1/src/django_redline/middleware.py +337 -0
- django_redline-0.2.0a1/src/django_redline/py.typed +0 -0
- django_redline-0.2.0a1/src/django_redline/runtime.py +141 -0
- django_redline-0.2.0a1/src/django_redline/scan.py +336 -0
- django_redline-0.2.0a1/src/django_redline/suggest.py +1121 -0
- django_redline-0.2.0a1/src/django_redline/transactions.py +81 -0
- django_redline-0.2.0a1/src/django_redline/urls.py +20 -0
- django_redline-0.2.0a1/src/django_redline/views.py +325 -0
- django_redline-0.2.0a1/tests/__init__.py +0 -0
- django_redline-0.2.0a1/tests/conftest.py +84 -0
- django_redline-0.2.0a1/tests/no_urls.py +1 -0
- django_redline-0.2.0a1/tests/security_urls.py +40 -0
- django_redline-0.2.0a1/tests/settings.py +77 -0
- django_redline-0.2.0a1/tests/test_access_policies.py +177 -0
- django_redline-0.2.0a1/tests/test_blocking_transactions.py +139 -0
- django_redline-0.2.0a1/tests/test_checks_commands.py +99 -0
- django_redline-0.2.0a1/tests/test_data_issues.py +161 -0
- django_redline-0.2.0a1/tests/test_drf.py +53 -0
- django_redline-0.2.0a1/tests/test_explain.py +48 -0
- django_redline-0.2.0a1/tests/test_hardening.py +154 -0
- django_redline-0.2.0a1/tests/test_middleware.py +224 -0
- django_redline-0.2.0a1/tests/test_ninja.py +117 -0
- django_redline-0.2.0a1/tests/test_scan.py +230 -0
- django_redline-0.2.0a1/tests/test_security_redaction.py +78 -0
- django_redline-0.2.0a1/tests/test_security_regressions.py +53 -0
- django_redline-0.2.0a1/tests/test_suggest.py +232 -0
- django_redline-0.2.0a1/tests/test_v02_adapter.py +296 -0
- django_redline-0.2.0a1/tests/test_views.py +131 -0
- django_redline-0.2.0a1/tests/testapp/__init__.py +0 -0
- django_redline-0.2.0a1/tests/testapp/drf_views.py +49 -0
- django_redline-0.2.0a1/tests/testapp/migrations/0001_initial.py +159 -0
- django_redline-0.2.0a1/tests/testapp/migrations/0002_article.py +24 -0
- django_redline-0.2.0a1/tests/testapp/migrations/__init__.py +0 -0
- django_redline-0.2.0a1/tests/testapp/models.py +55 -0
- django_redline-0.2.0a1/tests/testapp/ninja_api.py +67 -0
- django_redline-0.2.0a1/tests/testapp/serializers.py +23 -0
- django_redline-0.2.0a1/tests/testapp/templates/testapp/n1_scan.html +9 -0
- django_redline-0.2.0a1/tests/testapp/templates/testapp/orders.html +1 -0
- django_redline-0.2.0a1/tests/testapp/templates/testapp/page.html +1 -0
- django_redline-0.2.0a1/tests/testapp/templates/testapp/row.html +1 -0
- django_redline-0.2.0a1/tests/testapp/views.py +219 -0
- django_redline-0.2.0a1/tests/testapp/views_async_tx.py +87 -0
- django_redline-0.2.0a1/tests/testapp/views_data.py +50 -0
- django_redline-0.2.0a1/tests/urls.py +15 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
.venv/
|
|
4
|
+
venv/
|
|
5
|
+
dist/
|
|
6
|
+
build/
|
|
7
|
+
site/
|
|
8
|
+
.redline/
|
|
9
|
+
*.db
|
|
10
|
+
*.sqlite3
|
|
11
|
+
.pytest_cache/
|
|
12
|
+
.ruff_cache/
|
|
13
|
+
.coverage
|
|
14
|
+
htmlcov/
|
|
15
|
+
node_modules/
|
|
16
|
+
frontend/dist/
|
|
17
|
+
.DS_Store
|
|
18
|
+
frontend/screenshots/
|
|
19
|
+
|
|
20
|
+
# agent worktrees
|
|
21
|
+
.claude/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mahmoud Ahmed
|
|
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,229 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: django-redline
|
|
3
|
+
Version: 0.2.0a1
|
|
4
|
+
Summary: A modern request profiler for Django: SQL timelines, N+1 detection with fix diffs, one-click EXPLAIN, flamegraphs and a fast web UI. Async-correct.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Pythondeveloper6/redline
|
|
6
|
+
Project-URL: Documentation, https://pythondeveloper6.github.io/redline/django/
|
|
7
|
+
Project-URL: Source, https://github.com/Pythondeveloper6/redline
|
|
8
|
+
Project-URL: Issues, https://github.com/Pythondeveloper6/redline/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/Pythondeveloper6/redline/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: Mahmoud Ahmed <pythondeveloper6@gmail.com>
|
|
11
|
+
Maintainer-email: Mahmoud Ahmed <pythondeveloper6@gmail.com>
|
|
12
|
+
License-Expression: MIT
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Keywords: debug-toolbar,django,explain,flamegraph,n+1,performance,profiler,silk,sql
|
|
15
|
+
Classifier: Development Status :: 3 - Alpha
|
|
16
|
+
Classifier: Environment :: Web Environment
|
|
17
|
+
Classifier: Framework :: Django
|
|
18
|
+
Classifier: Framework :: Django :: 5.2
|
|
19
|
+
Classifier: Framework :: Django :: 6.0
|
|
20
|
+
Classifier: Framework :: Django :: 6.1
|
|
21
|
+
Classifier: Intended Audience :: Developers
|
|
22
|
+
Classifier: Operating System :: OS Independent
|
|
23
|
+
Classifier: Programming Language :: Python :: 3
|
|
24
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
27
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
28
|
+
Classifier: Topic :: Software Development :: Debuggers
|
|
29
|
+
Classifier: Topic :: System :: Monitoring
|
|
30
|
+
Classifier: Typing :: Typed
|
|
31
|
+
Requires-Python: >=3.12
|
|
32
|
+
Requires-Dist: django<6.2,>=5.2
|
|
33
|
+
Requires-Dist: redline-core==0.2.0a1
|
|
34
|
+
Provides-Extra: profile
|
|
35
|
+
Requires-Dist: redline-core[profile]==0.2.0a1; extra == 'profile'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
<p align="center">
|
|
39
|
+
<a href="https://pythondeveloper6.github.io/redline/">
|
|
40
|
+
<picture>
|
|
41
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Pythondeveloper6/redline/main/docs/assets/logo-dark.svg">
|
|
42
|
+
<img alt="Redline" src="https://raw.githubusercontent.com/Pythondeveloper6/redline/main/docs/assets/logo-light.svg" height="56">
|
|
43
|
+
</picture>
|
|
44
|
+
</a>
|
|
45
|
+
</p>
|
|
46
|
+
|
|
47
|
+
# django-redline
|
|
48
|
+
|
|
49
|
+
A modern request profiler for Django: SQL timelines, **N+1 detection with ready-to-apply
|
|
50
|
+
`select_related`/`prefetch_related` diffs**, one-click EXPLAIN, flamegraphs and a fast web UI.
|
|
51
|
+
It is async-correct (WSGI and ASGI, sync and async views). It does not touch your database:
|
|
52
|
+
traces live in their own SQLite file.
|
|
53
|
+
|
|
54
|
+
It replaces django-silk. Redline stores redacted data rather than plaintext secrets, never writes to
|
|
55
|
+
your app DB or records itself, supports async, groups N+1s, and adds EXPLAIN and flamegraphs.
|
|
56
|
+
|
|
57
|
+
> Status: `0.2.0a1`, alpha. Built on [`redline-core`](../redline-core).
|
|
58
|
+
|
|
59
|
+
## Install
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
pip install \
|
|
63
|
+
"django-redline @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/django-redline" \
|
|
64
|
+
"redline-core @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core"
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Not on PyPI yet: install from GitHub, naming `redline-core` in the same command (the adapter
|
|
68
|
+
pins it exactly). Docs: <https://pythondeveloper6.github.io/redline/>.
|
|
69
|
+
|
|
70
|
+
Add the extra to the core requirement for flamegraphs:
|
|
71
|
+
`"redline-core[profile] @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core"`.
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
# settings.py
|
|
75
|
+
INSTALLED_APPS = [..., "django_redline"]
|
|
76
|
+
|
|
77
|
+
MIDDLEWARE = [
|
|
78
|
+
"django.middleware.security.SecurityMiddleware",
|
|
79
|
+
# "django.middleware.gzip.GZipMiddleware", # if you use it, keep it above Redline
|
|
80
|
+
"django_redline.middleware.RedlineMiddleware", # as high as possible
|
|
81
|
+
"django.contrib.sessions.middleware.SessionMiddleware",
|
|
82
|
+
...
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
# urls.py
|
|
86
|
+
from django.urls import include, path
|
|
87
|
+
|
|
88
|
+
urlpatterns = [
|
|
89
|
+
...,
|
|
90
|
+
path("redline/", include("django_redline.urls")),
|
|
91
|
+
]
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Run your app, make some requests and open **`/redline/`** as a superuser.
|
|
95
|
+
|
|
96
|
+
## What you get
|
|
97
|
+
|
|
98
|
+
- **Requests**: every request with method, route template (`/orders/<int:pk>/`), view, status,
|
|
99
|
+
duration, query count and issue badges. Filter, search and live polling.
|
|
100
|
+
- **Request detail**: a waterfall of the span tree (middleware, then view, then SQL / cache / template
|
|
101
|
+
spans, plus your own `span()`s), SQL grouped by fingerprint with the project file:line that ran it,
|
|
102
|
+
redacted headers and bodies, and the traceback of unhandled exceptions.
|
|
103
|
+
- **Issues**: N+1s, duplicate queries, slow queries and query budgets, deduplicated across requests.
|
|
104
|
+
- **The Django fix suggester** maps the repeated SQL back to your models and relations, then finds
|
|
105
|
+
the queryset in your source and writes the patch:
|
|
106
|
+
|
|
107
|
+
```diff
|
|
108
|
+
--- a/shop/views.py
|
|
109
|
+
+++ b/shop/views.py
|
|
110
|
+
@@ -32,5 +32,5 @@
|
|
111
|
+
def order_list(request):
|
|
112
|
+
- orders = Order.objects.select_related("customer").order_by("-id")[:30]
|
|
113
|
+
+ orders = Order.objects.select_related("customer").prefetch_related("items").order_by("-id")[:30]
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
| Situation | Suggestion |
|
|
117
|
+
|---|---|
|
|
118
|
+
| reverse FK (`order.items.all()`) | `prefetch_related("items")` |
|
|
119
|
+
| forward FK / one-to-one (`item.product`) | `select_related("product")` |
|
|
120
|
+
| reverse one-to-one (`customer.profile`) | `select_related("profile")` |
|
|
121
|
+
| many-to-many, either side | `prefetch_related("tags")` / `prefetch_related("products")` |
|
|
122
|
+
| nested loops (`for item in order.items.all(): item.product`) | `prefetch_related("items__product")` on the outer queryset |
|
|
123
|
+
| `GenericRelation` / `GenericForeignKey` | `prefetch_related(...)` (GFK: low confidence) |
|
|
124
|
+
| the relation is filtered per row (`order.items.filter(...)`) | a `Prefetch(..., queryset=..., to_attr=...)` hint |
|
|
125
|
+
| loop in a template, generic `ListView` (`model = Order`) | diff on the `render()` queryset / adds `queryset = ...` to the view |
|
|
126
|
+
| DRF serializer reading a relation | targets the view's `queryset` / `get_queryset()` |
|
|
127
|
+
|
|
128
|
+
The fix is inserted before ordering and slicing, replaces a bare `.all()`, or extends an existing
|
|
129
|
+
`prefetch_related(...)`. When the queryset cannot be located you get a code hint with lower
|
|
130
|
+
confidence.
|
|
131
|
+
- **EXPLAIN** on any captured `SELECT`, run on `connections[alias]` inside a transaction that is
|
|
132
|
+
always rolled back (and `READ ONLY` on PostgreSQL). Plans are analysed for full scans, temp sorts
|
|
133
|
+
and spills, with `CREATE INDEX` suggestions. Works on SQLite, PostgreSQL and MySQL.
|
|
134
|
+
- **Flamegraphs**: add `?_redline=profile` to any URL (or send `X-Redline-Profile: 1`) to profile
|
|
135
|
+
that request with pyinstrument (needs the `profile` extra).
|
|
136
|
+
- **Load-test correlation**: an `X-Redline-Run: <id>;step=<n>` request header tags the trace.
|
|
137
|
+
|
|
138
|
+
## Settings
|
|
139
|
+
|
|
140
|
+
Everything is optional. `REDLINE` keys are case-insensitive, and unknown keys fail the system check
|
|
141
|
+
with a "did you mean" hint.
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
REDLINE = {
|
|
145
|
+
"ENABLED": True,
|
|
146
|
+
"SAMPLE_RATE": 1.0, # default 1.0 with DEBUG=True, 0.1 with DEBUG=False
|
|
147
|
+
"ALWAYS_KEEP_SLOWER_THAN_MS": 500,
|
|
148
|
+
"ALWAYS_KEEP_ERRORS": True,
|
|
149
|
+
"IGNORE_PATHS": ["/static/", "/media/", "/favicon.ico", "^/health"], # "^" = regex
|
|
150
|
+
"STORAGE_PATH": BASE_DIR / ".redline/redline.db", # the default; str or pathlib.Path
|
|
151
|
+
"N_PLUS_ONE_THRESHOLD": 5,
|
|
152
|
+
"SLOW_QUERY_MS": 100,
|
|
153
|
+
"TOO_MANY_QUERIES": 50,
|
|
154
|
+
"PROFILE": "opt_in", # off | opt_in | sampled | all
|
|
155
|
+
"EXPLAIN_ANALYZE": False, # ANALYZE executes the query: off by default
|
|
156
|
+
"MAX_ROWS": 10_000, "MAX_AGE_DAYS": 7, # 0 or None disables a retention rule
|
|
157
|
+
"MAX_SPANS_PER_TRACE": 2_000, # beyond it spans are counted, not stored
|
|
158
|
+
"PERMISSION": "myproject.redline.can_view", # Django-only, see below
|
|
159
|
+
"STORE": "myproject.redline.make_store", # Django-only: a custom Store (optional)
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
The full list is in the settings reference of the docs (`redline_core.conf.Settings`).
|
|
164
|
+
`PROJECT_ROOT` defaults to `BASE_DIR`. It decides which stack frames count as "your code".
|
|
165
|
+
|
|
166
|
+
## Security
|
|
167
|
+
|
|
168
|
+
- **Access**: superusers only by default (`user.is_active and user.is_superuser`; staff before 0.2). Override it with
|
|
169
|
+
`REDLINE["PERMISSION"]`, a callable `(request) -> bool` or its dotted path. Anonymous visitors to
|
|
170
|
+
the page are redirected to the admin login. The API answers `403` JSON. Redline's views also
|
|
171
|
+
enforce `ALLOWED_HOSTS` (against DNS rebinding) and the page sends `X-Frame-Options: DENY`.
|
|
172
|
+
- **CSRF**: the JSON API runs Django's own CSRF check on every request, even without
|
|
173
|
+
`CsrfViewMiddleware`. Mutating calls (`DELETE` traces, `POST api/explain`) need the token in the
|
|
174
|
+
CSRF header (`X-CSRFToken` by default). On HTTPS the Origin/Referer checks also apply. The page
|
|
175
|
+
embeds a fresh token in `<meta name="redline-csrf">`, so this also works with
|
|
176
|
+
`CSRF_COOKIE_HTTPONLY` / `CSRF_USE_SESSIONS`. Failures are a JSON `403` `csrf_failed`.
|
|
177
|
+
- **Redaction**: `Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key` headers and
|
|
178
|
+
password/token/secret-like keys in query strings, bodies and SQL params are masked before anything
|
|
179
|
+
is stored.
|
|
180
|
+
- Requests to Redline's own URLs are never recorded. Its storage is a separate SQLite file, never a
|
|
181
|
+
Django connection.
|
|
182
|
+
|
|
183
|
+
## Your own spans
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
from django_redline import span
|
|
187
|
+
|
|
188
|
+
@span("pricing.compute")
|
|
189
|
+
def compute(order): ...
|
|
190
|
+
|
|
191
|
+
with span("render-pdf", pages=3):
|
|
192
|
+
...
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Operations
|
|
196
|
+
|
|
197
|
+
- `manage.py redline_clear [--noinput]` deletes every trace.
|
|
198
|
+
- `manage.py redline_prune [--max-age-days N] [--max-rows N]` applies retention now. The writer also
|
|
199
|
+
prunes as it goes.
|
|
200
|
+
- System checks (`manage.py check`):
|
|
201
|
+
|
|
202
|
+
| ID | Problem |
|
|
203
|
+
|---|---|
|
|
204
|
+
| `E001` | invalid `REDLINE` |
|
|
205
|
+
| `E002` | storage not writable |
|
|
206
|
+
| `W001` | middleware missing |
|
|
207
|
+
| `W002` | `GZipMiddleware` inside Redline |
|
|
208
|
+
| `W003` | Redline listed after middleware it should time |
|
|
209
|
+
| `W004` | URLs not mounted |
|
|
210
|
+
| `W005` | `DEBUG=False` with `SAMPLE_RATE=1.0` |
|
|
211
|
+
|
|
212
|
+
- Writes happen on a background thread through a bounded queue. Under overload, traces are dropped
|
|
213
|
+
and counted rather than slowing requests.
|
|
214
|
+
|
|
215
|
+
## How it hooks in
|
|
216
|
+
|
|
217
|
+
- The middleware is sync and async capable. SQL goes through `connection.execute_wrapper` on every
|
|
218
|
+
connection. Cache spans come from wrapping the backends that `caches` creates. Template spans come
|
|
219
|
+
from `Template.render`, and the view span from `BaseHandler.make_view_atomic`.
|
|
220
|
+
- Each hook is a single `ContextVar` lookup when nothing is being recorded.
|
|
221
|
+
- Queries run from library code (generic views, DRF, lazily rendered `TemplateResponse`s) are
|
|
222
|
+
attributed to the project view that handled the request.
|
|
223
|
+
|
|
224
|
+
Supports Django 5.2, 6.0 and 6.1 on Python 3.12+. A runnable demo is in
|
|
225
|
+
[`examples/django`](https://github.com/Pythondeveloper6/redline/blob/main/examples/django).
|
|
226
|
+
|
|
227
|
+
## License
|
|
228
|
+
|
|
229
|
+
MIT
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://pythondeveloper6.github.io/redline/">
|
|
3
|
+
<picture>
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Pythondeveloper6/redline/main/docs/assets/logo-dark.svg">
|
|
5
|
+
<img alt="Redline" src="https://raw.githubusercontent.com/Pythondeveloper6/redline/main/docs/assets/logo-light.svg" height="56">
|
|
6
|
+
</picture>
|
|
7
|
+
</a>
|
|
8
|
+
</p>
|
|
9
|
+
|
|
10
|
+
# django-redline
|
|
11
|
+
|
|
12
|
+
A modern request profiler for Django: SQL timelines, **N+1 detection with ready-to-apply
|
|
13
|
+
`select_related`/`prefetch_related` diffs**, one-click EXPLAIN, flamegraphs and a fast web UI.
|
|
14
|
+
It is async-correct (WSGI and ASGI, sync and async views). It does not touch your database:
|
|
15
|
+
traces live in their own SQLite file.
|
|
16
|
+
|
|
17
|
+
It replaces django-silk. Redline stores redacted data rather than plaintext secrets, never writes to
|
|
18
|
+
your app DB or records itself, supports async, groups N+1s, and adds EXPLAIN and flamegraphs.
|
|
19
|
+
|
|
20
|
+
> Status: `0.2.0a1`, alpha. Built on [`redline-core`](../redline-core).
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install \
|
|
26
|
+
"django-redline @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/django-redline" \
|
|
27
|
+
"redline-core @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core"
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Not on PyPI yet: install from GitHub, naming `redline-core` in the same command (the adapter
|
|
31
|
+
pins it exactly). Docs: <https://pythondeveloper6.github.io/redline/>.
|
|
32
|
+
|
|
33
|
+
Add the extra to the core requirement for flamegraphs:
|
|
34
|
+
`"redline-core[profile] @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core"`.
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
# settings.py
|
|
38
|
+
INSTALLED_APPS = [..., "django_redline"]
|
|
39
|
+
|
|
40
|
+
MIDDLEWARE = [
|
|
41
|
+
"django.middleware.security.SecurityMiddleware",
|
|
42
|
+
# "django.middleware.gzip.GZipMiddleware", # if you use it, keep it above Redline
|
|
43
|
+
"django_redline.middleware.RedlineMiddleware", # as high as possible
|
|
44
|
+
"django.contrib.sessions.middleware.SessionMiddleware",
|
|
45
|
+
...
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
# urls.py
|
|
49
|
+
from django.urls import include, path
|
|
50
|
+
|
|
51
|
+
urlpatterns = [
|
|
52
|
+
...,
|
|
53
|
+
path("redline/", include("django_redline.urls")),
|
|
54
|
+
]
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Run your app, make some requests and open **`/redline/`** as a superuser.
|
|
58
|
+
|
|
59
|
+
## What you get
|
|
60
|
+
|
|
61
|
+
- **Requests**: every request with method, route template (`/orders/<int:pk>/`), view, status,
|
|
62
|
+
duration, query count and issue badges. Filter, search and live polling.
|
|
63
|
+
- **Request detail**: a waterfall of the span tree (middleware, then view, then SQL / cache / template
|
|
64
|
+
spans, plus your own `span()`s), SQL grouped by fingerprint with the project file:line that ran it,
|
|
65
|
+
redacted headers and bodies, and the traceback of unhandled exceptions.
|
|
66
|
+
- **Issues**: N+1s, duplicate queries, slow queries and query budgets, deduplicated across requests.
|
|
67
|
+
- **The Django fix suggester** maps the repeated SQL back to your models and relations, then finds
|
|
68
|
+
the queryset in your source and writes the patch:
|
|
69
|
+
|
|
70
|
+
```diff
|
|
71
|
+
--- a/shop/views.py
|
|
72
|
+
+++ b/shop/views.py
|
|
73
|
+
@@ -32,5 +32,5 @@
|
|
74
|
+
def order_list(request):
|
|
75
|
+
- orders = Order.objects.select_related("customer").order_by("-id")[:30]
|
|
76
|
+
+ orders = Order.objects.select_related("customer").prefetch_related("items").order_by("-id")[:30]
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
| Situation | Suggestion |
|
|
80
|
+
|---|---|
|
|
81
|
+
| reverse FK (`order.items.all()`) | `prefetch_related("items")` |
|
|
82
|
+
| forward FK / one-to-one (`item.product`) | `select_related("product")` |
|
|
83
|
+
| reverse one-to-one (`customer.profile`) | `select_related("profile")` |
|
|
84
|
+
| many-to-many, either side | `prefetch_related("tags")` / `prefetch_related("products")` |
|
|
85
|
+
| nested loops (`for item in order.items.all(): item.product`) | `prefetch_related("items__product")` on the outer queryset |
|
|
86
|
+
| `GenericRelation` / `GenericForeignKey` | `prefetch_related(...)` (GFK: low confidence) |
|
|
87
|
+
| the relation is filtered per row (`order.items.filter(...)`) | a `Prefetch(..., queryset=..., to_attr=...)` hint |
|
|
88
|
+
| loop in a template, generic `ListView` (`model = Order`) | diff on the `render()` queryset / adds `queryset = ...` to the view |
|
|
89
|
+
| DRF serializer reading a relation | targets the view's `queryset` / `get_queryset()` |
|
|
90
|
+
|
|
91
|
+
The fix is inserted before ordering and slicing, replaces a bare `.all()`, or extends an existing
|
|
92
|
+
`prefetch_related(...)`. When the queryset cannot be located you get a code hint with lower
|
|
93
|
+
confidence.
|
|
94
|
+
- **EXPLAIN** on any captured `SELECT`, run on `connections[alias]` inside a transaction that is
|
|
95
|
+
always rolled back (and `READ ONLY` on PostgreSQL). Plans are analysed for full scans, temp sorts
|
|
96
|
+
and spills, with `CREATE INDEX` suggestions. Works on SQLite, PostgreSQL and MySQL.
|
|
97
|
+
- **Flamegraphs**: add `?_redline=profile` to any URL (or send `X-Redline-Profile: 1`) to profile
|
|
98
|
+
that request with pyinstrument (needs the `profile` extra).
|
|
99
|
+
- **Load-test correlation**: an `X-Redline-Run: <id>;step=<n>` request header tags the trace.
|
|
100
|
+
|
|
101
|
+
## Settings
|
|
102
|
+
|
|
103
|
+
Everything is optional. `REDLINE` keys are case-insensitive, and unknown keys fail the system check
|
|
104
|
+
with a "did you mean" hint.
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
REDLINE = {
|
|
108
|
+
"ENABLED": True,
|
|
109
|
+
"SAMPLE_RATE": 1.0, # default 1.0 with DEBUG=True, 0.1 with DEBUG=False
|
|
110
|
+
"ALWAYS_KEEP_SLOWER_THAN_MS": 500,
|
|
111
|
+
"ALWAYS_KEEP_ERRORS": True,
|
|
112
|
+
"IGNORE_PATHS": ["/static/", "/media/", "/favicon.ico", "^/health"], # "^" = regex
|
|
113
|
+
"STORAGE_PATH": BASE_DIR / ".redline/redline.db", # the default; str or pathlib.Path
|
|
114
|
+
"N_PLUS_ONE_THRESHOLD": 5,
|
|
115
|
+
"SLOW_QUERY_MS": 100,
|
|
116
|
+
"TOO_MANY_QUERIES": 50,
|
|
117
|
+
"PROFILE": "opt_in", # off | opt_in | sampled | all
|
|
118
|
+
"EXPLAIN_ANALYZE": False, # ANALYZE executes the query: off by default
|
|
119
|
+
"MAX_ROWS": 10_000, "MAX_AGE_DAYS": 7, # 0 or None disables a retention rule
|
|
120
|
+
"MAX_SPANS_PER_TRACE": 2_000, # beyond it spans are counted, not stored
|
|
121
|
+
"PERMISSION": "myproject.redline.can_view", # Django-only, see below
|
|
122
|
+
"STORE": "myproject.redline.make_store", # Django-only: a custom Store (optional)
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
The full list is in the settings reference of the docs (`redline_core.conf.Settings`).
|
|
127
|
+
`PROJECT_ROOT` defaults to `BASE_DIR`. It decides which stack frames count as "your code".
|
|
128
|
+
|
|
129
|
+
## Security
|
|
130
|
+
|
|
131
|
+
- **Access**: superusers only by default (`user.is_active and user.is_superuser`; staff before 0.2). Override it with
|
|
132
|
+
`REDLINE["PERMISSION"]`, a callable `(request) -> bool` or its dotted path. Anonymous visitors to
|
|
133
|
+
the page are redirected to the admin login. The API answers `403` JSON. Redline's views also
|
|
134
|
+
enforce `ALLOWED_HOSTS` (against DNS rebinding) and the page sends `X-Frame-Options: DENY`.
|
|
135
|
+
- **CSRF**: the JSON API runs Django's own CSRF check on every request, even without
|
|
136
|
+
`CsrfViewMiddleware`. Mutating calls (`DELETE` traces, `POST api/explain`) need the token in the
|
|
137
|
+
CSRF header (`X-CSRFToken` by default). On HTTPS the Origin/Referer checks also apply. The page
|
|
138
|
+
embeds a fresh token in `<meta name="redline-csrf">`, so this also works with
|
|
139
|
+
`CSRF_COOKIE_HTTPONLY` / `CSRF_USE_SESSIONS`. Failures are a JSON `403` `csrf_failed`.
|
|
140
|
+
- **Redaction**: `Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key` headers and
|
|
141
|
+
password/token/secret-like keys in query strings, bodies and SQL params are masked before anything
|
|
142
|
+
is stored.
|
|
143
|
+
- Requests to Redline's own URLs are never recorded. Its storage is a separate SQLite file, never a
|
|
144
|
+
Django connection.
|
|
145
|
+
|
|
146
|
+
## Your own spans
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
from django_redline import span
|
|
150
|
+
|
|
151
|
+
@span("pricing.compute")
|
|
152
|
+
def compute(order): ...
|
|
153
|
+
|
|
154
|
+
with span("render-pdf", pages=3):
|
|
155
|
+
...
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Operations
|
|
159
|
+
|
|
160
|
+
- `manage.py redline_clear [--noinput]` deletes every trace.
|
|
161
|
+
- `manage.py redline_prune [--max-age-days N] [--max-rows N]` applies retention now. The writer also
|
|
162
|
+
prunes as it goes.
|
|
163
|
+
- System checks (`manage.py check`):
|
|
164
|
+
|
|
165
|
+
| ID | Problem |
|
|
166
|
+
|---|---|
|
|
167
|
+
| `E001` | invalid `REDLINE` |
|
|
168
|
+
| `E002` | storage not writable |
|
|
169
|
+
| `W001` | middleware missing |
|
|
170
|
+
| `W002` | `GZipMiddleware` inside Redline |
|
|
171
|
+
| `W003` | Redline listed after middleware it should time |
|
|
172
|
+
| `W004` | URLs not mounted |
|
|
173
|
+
| `W005` | `DEBUG=False` with `SAMPLE_RATE=1.0` |
|
|
174
|
+
|
|
175
|
+
- Writes happen on a background thread through a bounded queue. Under overload, traces are dropped
|
|
176
|
+
and counted rather than slowing requests.
|
|
177
|
+
|
|
178
|
+
## How it hooks in
|
|
179
|
+
|
|
180
|
+
- The middleware is sync and async capable. SQL goes through `connection.execute_wrapper` on every
|
|
181
|
+
connection. Cache spans come from wrapping the backends that `caches` creates. Template spans come
|
|
182
|
+
from `Template.render`, and the view span from `BaseHandler.make_view_atomic`.
|
|
183
|
+
- Each hook is a single `ContextVar` lookup when nothing is being recorded.
|
|
184
|
+
- Queries run from library code (generic views, DRF, lazily rendered `TemplateResponse`s) are
|
|
185
|
+
attributed to the project view that handled the request.
|
|
186
|
+
|
|
187
|
+
Supports Django 5.2, 6.0 and 6.1 on Python 3.12+. A runnable demo is in
|
|
188
|
+
[`examples/django`](https://github.com/Pythondeveloper6/redline/blob/main/examples/django).
|
|
189
|
+
|
|
190
|
+
## License
|
|
191
|
+
|
|
192
|
+
MIT
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "django-redline"
|
|
7
|
+
version = "0.2.0a1"
|
|
8
|
+
description = "A modern request profiler for Django: SQL timelines, N+1 detection with fix diffs, one-click EXPLAIN, flamegraphs and a fast web UI. Async-correct."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Mahmoud Ahmed", email = "pythondeveloper6@gmail.com" }]
|
|
14
|
+
maintainers = [{ name = "Mahmoud Ahmed", email = "pythondeveloper6@gmail.com" }]
|
|
15
|
+
keywords = [
|
|
16
|
+
"django",
|
|
17
|
+
"profiler",
|
|
18
|
+
"silk",
|
|
19
|
+
"debug-toolbar",
|
|
20
|
+
"performance",
|
|
21
|
+
"n+1",
|
|
22
|
+
"sql",
|
|
23
|
+
"explain",
|
|
24
|
+
"flamegraph",
|
|
25
|
+
]
|
|
26
|
+
classifiers = [
|
|
27
|
+
"Development Status :: 3 - Alpha",
|
|
28
|
+
"Environment :: Web Environment",
|
|
29
|
+
"Framework :: Django",
|
|
30
|
+
"Framework :: Django :: 5.2",
|
|
31
|
+
"Framework :: Django :: 6.0",
|
|
32
|
+
"Framework :: Django :: 6.1",
|
|
33
|
+
"Intended Audience :: Developers",
|
|
34
|
+
"Operating System :: OS Independent",
|
|
35
|
+
"Programming Language :: Python :: 3",
|
|
36
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
37
|
+
"Programming Language :: Python :: 3.12",
|
|
38
|
+
"Programming Language :: Python :: 3.13",
|
|
39
|
+
"Programming Language :: Python :: 3.14",
|
|
40
|
+
"Topic :: Software Development :: Debuggers",
|
|
41
|
+
"Topic :: System :: Monitoring",
|
|
42
|
+
"Typing :: Typed",
|
|
43
|
+
]
|
|
44
|
+
# Lockstep: the adapter pins the exact core release it was tested with. Django is
|
|
45
|
+
# upper-bounded on purpose: the bound moves only in the commit that adds the next
|
|
46
|
+
# Django to the CI matrix.
|
|
47
|
+
dependencies = ["redline-core==0.2.0a1", "Django>=5.2,<6.2"]
|
|
48
|
+
|
|
49
|
+
[project.optional-dependencies]
|
|
50
|
+
profile = ["redline-core[profile]==0.2.0a1"]
|
|
51
|
+
|
|
52
|
+
[project.urls]
|
|
53
|
+
Homepage = "https://github.com/Pythondeveloper6/redline"
|
|
54
|
+
Documentation = "https://pythondeveloper6.github.io/redline/django/"
|
|
55
|
+
Source = "https://github.com/Pythondeveloper6/redline"
|
|
56
|
+
Issues = "https://github.com/Pythondeveloper6/redline/issues"
|
|
57
|
+
Changelog = "https://github.com/Pythondeveloper6/redline/blob/main/CHANGELOG.md"
|
|
58
|
+
|
|
59
|
+
[dependency-groups]
|
|
60
|
+
dev = [
|
|
61
|
+
"pytest>=8.3",
|
|
62
|
+
"pytest-django>=4.9",
|
|
63
|
+
"djangorestframework>=3.15",
|
|
64
|
+
"pytest-asyncio>=0.24",
|
|
65
|
+
"ruff>=0.8",
|
|
66
|
+
"pyinstrument>=5.0",
|
|
67
|
+
"django-ninja>=1.3",
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
[tool.uv.sources]
|
|
71
|
+
redline-core = { workspace = true }
|
|
72
|
+
|
|
73
|
+
[tool.hatch.build.targets.wheel]
|
|
74
|
+
packages = ["src/django_redline"]
|
|
75
|
+
exclude = ["**/__pycache__", "**/*.py[cod]", "**/.DS_Store"]
|
|
76
|
+
|
|
77
|
+
[tool.hatch.build.targets.sdist]
|
|
78
|
+
include = ["/src/django_redline", "/tests", "/README.md", "/LICENSE"]
|
|
79
|
+
exclude = ["**/__pycache__", "**/*.py[cod]", "**/.DS_Store"]
|
|
80
|
+
|
|
81
|
+
[tool.pytest.ini_options]
|
|
82
|
+
DJANGO_SETTINGS_MODULE = "tests.settings"
|
|
83
|
+
pythonpath = ["."]
|
|
84
|
+
testpaths = ["tests"]
|
|
85
|
+
addopts = "--strict-markers -q"
|
|
86
|
+
asyncio_mode = "auto"
|
|
87
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
88
|
+
|
|
89
|
+
[tool.ruff]
|
|
90
|
+
extend = "../../pyproject.toml"
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""django-redline: the Django adapter for Redline.
|
|
2
|
+
|
|
3
|
+
Add ``"django_redline"`` to ``INSTALLED_APPS``, ``"django_redline.middleware.RedlineMiddleware"``
|
|
4
|
+
near the top of ``MIDDLEWARE`` and ``path("redline/", include("django_redline.urls"))`` to
|
|
5
|
+
your URLconf. Every request is then recorded – SQL, cache and template spans, N+1 and
|
|
6
|
+
duplicate-query issues with ``select_related``/``prefetch_related`` fix diffs, one-click
|
|
7
|
+
EXPLAIN and opt-in flamegraphs – and browsable at ``/redline/``.
|
|
8
|
+
|
|
9
|
+
User code can time its own blocks with :func:`span` (re-exported from ``redline_core``)::
|
|
10
|
+
|
|
11
|
+
from django_redline import span
|
|
12
|
+
|
|
13
|
+
@span("pricing.compute")
|
|
14
|
+
def compute_price(order): ...
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from redline_core import span
|
|
20
|
+
|
|
21
|
+
__version__ = "0.2.0a1"
|
|
22
|
+
|
|
23
|
+
__all__ = ["__version__", "span"]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Django REST framework serialization as ``serializer`` spans.
|
|
2
|
+
|
|
3
|
+
``BaseSerializer.data`` is where DRF turns an instance (or queryset) into primitives, for
|
|
4
|
+
``Serializer``, ``ModelSerializer`` and ``ListSerializer`` alike (their ``data`` properties
|
|
5
|
+
call it through ``super()``), so that one property is wrapped. Only the *outermost* access
|
|
6
|
+
is recorded: nested serializers run inside their parent's ``to_representation`` and
|
|
7
|
+
serializers built by hand inside a ``SerializerMethodField`` are covered by the parent's
|
|
8
|
+
span. DRF is optional – without it nothing happens – and outside a traced request the
|
|
9
|
+
wrapper costs one ``ContextVar.get()``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import time
|
|
15
|
+
from contextvars import ContextVar
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from redline_core import record_span
|
|
19
|
+
from redline_core.recorder import current
|
|
20
|
+
|
|
21
|
+
__all__ = ["install_drf", "uninstall_drf"]
|
|
22
|
+
|
|
23
|
+
_perf = time.perf_counter
|
|
24
|
+
_original: list[Any] = []
|
|
25
|
+
_inside: ContextVar[bool] = ContextVar("redline_drf", default=False)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def install_drf() -> bool:
|
|
29
|
+
"""Patch ``BaseSerializer.data``; ``False`` when DRF is not installed. Idempotent."""
|
|
30
|
+
from django.apps import apps
|
|
31
|
+
|
|
32
|
+
if not apps.is_installed("rest_framework"):
|
|
33
|
+
return False
|
|
34
|
+
try:
|
|
35
|
+
from rest_framework.serializers import BaseSerializer
|
|
36
|
+
except ImportError:
|
|
37
|
+
return False
|
|
38
|
+
if _original:
|
|
39
|
+
return True
|
|
40
|
+
prop = BaseSerializer.__dict__["data"]
|
|
41
|
+
fget = prop.fget
|
|
42
|
+
_original.append(prop)
|
|
43
|
+
|
|
44
|
+
def data(self: Any) -> Any:
|
|
45
|
+
if _inside.get() or current() is None:
|
|
46
|
+
return fget(self)
|
|
47
|
+
token = _inside.set(True)
|
|
48
|
+
start = _perf()
|
|
49
|
+
result = None
|
|
50
|
+
try:
|
|
51
|
+
result = fget(self)
|
|
52
|
+
return result
|
|
53
|
+
finally:
|
|
54
|
+
_inside.reset(token)
|
|
55
|
+
duration = _perf() - start
|
|
56
|
+
many = hasattr(self, "child")
|
|
57
|
+
name = type(self.child if many else self).__name__
|
|
58
|
+
items = None
|
|
59
|
+
if many and result is not None:
|
|
60
|
+
try:
|
|
61
|
+
items = len(result)
|
|
62
|
+
except TypeError:
|
|
63
|
+
items = None
|
|
64
|
+
record_span(
|
|
65
|
+
"serializer",
|
|
66
|
+
f"{name}.data",
|
|
67
|
+
start,
|
|
68
|
+
duration,
|
|
69
|
+
{"library": "drf", "serializer": name, "items": items, "many": many},
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
BaseSerializer.data = property(data, prop.fset, prop.fdel, prop.__doc__) # type: ignore[assignment]
|
|
73
|
+
return True
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def uninstall_drf() -> None:
|
|
77
|
+
"""Undo :func:`install_drf`."""
|
|
78
|
+
if not _original:
|
|
79
|
+
return
|
|
80
|
+
from rest_framework.serializers import BaseSerializer
|
|
81
|
+
|
|
82
|
+
BaseSerializer.data = _original.pop() # type: ignore[assignment]
|