sendproof-django 0.1.0a2__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.
@@ -0,0 +1,36 @@
1
+ .DS_Store
2
+ .vs/
3
+ .idea/
4
+ **/bin/
5
+ # The Ruby binding's scripts (prepare, test, fixture) are source, not build output.
6
+ !adapters/ruby/bin/
7
+ **/obj/
8
+ **/node_modules/
9
+ artifacts/
10
+ TestResults/
11
+ *.user
12
+ *.db
13
+ *.db-shm
14
+ *.db-wal
15
+ *.nupkg
16
+ *.snupkg
17
+ __pycache__/
18
+
19
+ # Binding build output, local toolchains and dependency caches
20
+ **/target/
21
+ **/vendor/
22
+ # Third-party ES modules the workbench imports directly; built by tools/vendor-journeys-libs.mjs.
23
+ !ui/vendor/
24
+ **/.venv/
25
+ **/.gradle/
26
+ **/.gradle-home/
27
+ adapters/java/**/build/
28
+ adapters/java/build/
29
+ adapters/python/dist/
30
+ adapters/php/dist/
31
+ *.egg-info/
32
+ .pytest_cache/
33
+ .phpunit.cache/
34
+
35
+ # Demo cookie keys, kept beside the demo database
36
+ store-demo.keys/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sendproof contributors
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,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: sendproof-django
3
+ Version: 0.1.0a2
4
+ Summary: Sendproof workbench, rollback previews and observed sends for Django, Django REST framework and Django Ninja, with Django ORM capture.
5
+ Project-URL: Homepage, https://github.com/mprync/sendproof/tree/main/adapters/python/django
6
+ Project-URL: Repository, https://github.com/mprync/sendproof
7
+ Project-URL: Issues, https://github.com/mprync/sendproof/issues
8
+ Project-URL: Changelog, https://github.com/mprync/sendproof/blob/main/CHANGELOG.md
9
+ Author: Sendproof contributors
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: api-testing,django,django-ninja,djangorestframework,openapi,rollback,swagger,testing
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: Django
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Software Development :: Testing
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: django>=4.2
28
+ Requires-Dist: sendproof-core==0.1.0a2
29
+ Description-Content-Type: text/markdown
30
+
31
+ # sendproof-django
32
+
33
+ Serves the [Sendproof](../../spec/README.md) workbench from a Django project and runs rollback
34
+ **Preview** and **Observed Send** through Django's URL resolver, middleware and views. Works with
35
+ plain views, Django REST framework and Django Ninja, and captures changes through the Django ORM.
36
+
37
+ ```sh
38
+ pip install sendproof-django
39
+ ```
40
+
41
+ ```python
42
+ # settings.py
43
+ MIDDLEWARE = [
44
+ # ... sessions, authentication, your own middleware ...
45
+ "sendproof_django.middleware.SendproofMiddleware", # last
46
+ ]
47
+
48
+ SENDPROOF = {
49
+ "ENVIRONMENT": "Development", # off in any environment not listed
50
+ "PROVIDER": "sendproof_django.DjangoOrmPreview", # opt in to rollback previews
51
+ "OPENAPI_URL": "/api/openapi.json",
52
+ "AUTH_PROVIDERS": [{"label": "Password", "kind": "cookie", "url": "/auth/sign-in"}],
53
+ }
54
+ ```
55
+
56
+ The workbench is at `/sendproof/`. It is **off** unless `ENVIRONMENT` (default `$SENDPROOF_ENVIRONMENT`,
57
+ else `Production`) is in `ENVIRONMENTS` (default `["Development"]`).
58
+
59
+ ## Marking operations
60
+
61
+ ```python
62
+ from sendproof_django import preview
63
+
64
+ @preview(methods=["POST"]) # function view: methods accepted for previews
65
+ def create_item(request): ...
66
+
67
+ class Things(APIView): # Django REST framework (or any class-based view)
68
+ @preview # decorate the handler method
69
+ def post(self, request): ...
70
+
71
+ @api.post("/items") # Django Ninja: below the route decorator
72
+ @preview
73
+ def create_item(request, payload: ItemIn): ...
74
+ ```
75
+
76
+ Only marked operations are advertised and accepted. Without `methods`, a function view accepts
77
+ `POST`, `PUT`, `PATCH` and `DELETE`. Class-based handlers and Ninja operations use their own HTTP
78
+ methods. Routes written with `re_path` have no portable OpenAPI template and are not advertised.
79
+
80
+ ## Settings
81
+
82
+ | Key | Meaning |
83
+ | --- | --- |
84
+ | `PROVIDER` | `DjangoOrmPreview(using=("default",), database="label")`, an instance or dotted path. Without one, nothing is advertised and previews answer 503. |
85
+ | `IDENTITY` | `(request) -> Identity \| None` (callable or dotted path). Defaults to `request.user` when authenticated (subject = primary key). |
86
+ | `AUTHORIZE` | `(request, identity) -> bool`. Optional workbench policy (401/403). |
87
+ | `ENVIRONMENT`, `ENVIRONMENTS` | Where the workbench is on. |
88
+ | `API_NAME`, `OPENAPI_URL`, `DOCUMENTS`, `AUTH_PROVIDERS`, `FIELD_MODULES` | Discovery. `OPENAPI_URL` defaults to `/openapi.json`. |
89
+ | `INCLUDE_SQL_PARAMETER_VALUES` | Show SQL values (Development only by default). |
90
+ | `TRACE_TTL` | Seconds a trace is kept (default 300). |
91
+
92
+ Unknown keys raise `ValueError` so typos are not silently ignored.
93
+
94
+ ## How it works
95
+
96
+ A request to `/sendproof/_preview/<path>` with exactly `Prefer: tx=rollback` is resolved with your
97
+ URLconf, then a copy of the request is sent through the complete `MIDDLEWARE` chain and the real
98
+ view, in-process, with `transaction.atomic()` open on every enrolled database. Every middleware,
99
+ including path-based ones, sees the target path, and session changes stay on the copy, so they are
100
+ neither saved by the outer `SessionMiddleware` nor sent as a cookie. Sendproof checks again, last
101
+ in the chain, that the request still resolves to the marked view and method. The response is buffered (1 MiB cap),
102
+ the atomic blocks are rolled back and confirmed, and only then does the middleware answer with the
103
+ envelope. `Prefer: trace` on the original URL commits normally and adds `X-Sendproof-Trace`; the
104
+ same caller can fetch it from `/sendproof/_api/traces/{id}` until it expires.
105
+
106
+ - Commit semantics follow Django: a nested `atomic()` releases a savepoint, `transaction.on_commit`
107
+ callbacks are discarded with the rollback, and a handler that handles an `IntegrityError`
108
+ behaves as usual.
109
+ - A 401 or 403 is always a denial and never an envelope. Other statuses, including 409 and the
110
+ 400 or 422 your framework returns for invalid input, are the application's answer. An unhandled
111
+ exception becomes an unconfirmed 500.
112
+ - CSRF protection runs against the target view exactly as for a normal request. Sendproof
113
+ sends no CSRF token, so previews of views protected by it are rejected unless the view is
114
+ exempt or authenticates another way, as API views usually do.
115
+ - Mounted under a prefix (`SCRIPT_NAME`/`FORCE_SCRIPT_NAME`), discovery URLs include it. Django
116
+ Ninja prefixes OpenAPI paths with the script prefix; serve its schema with
117
+ `api.get_openapi_schema(path_prefix="/")` so the paths match the operations the workbench lists.
118
+
119
+ ## Change capture and coverage
120
+
121
+ Changes come from `pre_save`/`post_save`/`pre_delete`/`post_delete`: inserts, updates and deletes made
122
+ with `Model.save()`, `Model.objects.create()` and `Model.delete()`, including cascades the ORM
123
+ performs. The row before an update or delete is read from the database; that read is not logged.
124
+
125
+ - **Not captured (but rolled back):** `QuerySet.update()`, `bulk_create()`, `bulk_update()`, raw SQL,
126
+ triggers and cascades done by the database. Their SQL appears in the logs. Rows are never
127
+ synthesized.
128
+ - **Transaction-control SQL is refused before it is sent** and the Preview answers 500: `COMMIT`,
129
+ `ROLLBACK` (not `ROLLBACK TO SAVEPOINT`), `BEGIN`, `SET autocommit`, the internal
130
+ `sendproof_preview` savepoint, and on MySQL, MariaDB and Oracle the statements those databases
131
+ commit implicitly (DDL other than `TEMPORARY` tables, `LOCK TABLES`, `GRANT` and the rest of
132
+ MySQL's list). On MySQL and MariaDB `CALL` is refused too, because a procedure can commit,
133
+ unless you declare it safe by exact name (case-insensitive, no wildcards; the binding trusts the
134
+ declaration):
135
+
136
+ ```python
137
+ SENDPROOF = {"PROVIDER": lambda: DjangoOrmPreview(safe_procedures=["refresh_totals"]), ...}
138
+ ```
139
+
140
+ - **Backstop on every database:** the Preview opens its transaction with
141
+ `SAVEPOINT sendproof_preview` and checks, before rolling back, that it still exists. Any commit
142
+ erases it, so a Preview whose transaction was committed anyway (on the driver's own connection,
143
+ say, which then begins a new transaction) answers 500 without confirmation (the writes before
144
+ that commit stay).
145
+ - **Deadlocks on MySQL and MariaDB:** a deadlock (1213), or a lock wait timeout (1205) with
146
+ `innodb_rollback_on_timeout` on, rolls back the whole Preview transaction. The handler still gets
147
+ the original error; every later statement in that Preview except Django's own savepoint
148
+ rollbacks is refused before it is sent, and the Preview answers 500 without confirmation. The
149
+ lock wait timeout case shares the deadlock code path and is covered by unit tests only, because
150
+ `innodb_rollback_on_timeout` can be set only at server startup.
151
+ - Enrolled aliases share the request thread's connection. Work in other threads, other databases
152
+ you did not list, caches, files and other services are not rolled back.
153
+ - Synchronous views only. Async views and ASGI deployments are not tested.
154
+ - The inner response object is not closed during a preview, so Django's `request_finished`
155
+ connection cleanup cannot end the transaction early.
@@ -0,0 +1,125 @@
1
+ # sendproof-django
2
+
3
+ Serves the [Sendproof](../../spec/README.md) workbench from a Django project and runs rollback
4
+ **Preview** and **Observed Send** through Django's URL resolver, middleware and views. Works with
5
+ plain views, Django REST framework and Django Ninja, and captures changes through the Django ORM.
6
+
7
+ ```sh
8
+ pip install sendproof-django
9
+ ```
10
+
11
+ ```python
12
+ # settings.py
13
+ MIDDLEWARE = [
14
+ # ... sessions, authentication, your own middleware ...
15
+ "sendproof_django.middleware.SendproofMiddleware", # last
16
+ ]
17
+
18
+ SENDPROOF = {
19
+ "ENVIRONMENT": "Development", # off in any environment not listed
20
+ "PROVIDER": "sendproof_django.DjangoOrmPreview", # opt in to rollback previews
21
+ "OPENAPI_URL": "/api/openapi.json",
22
+ "AUTH_PROVIDERS": [{"label": "Password", "kind": "cookie", "url": "/auth/sign-in"}],
23
+ }
24
+ ```
25
+
26
+ The workbench is at `/sendproof/`. It is **off** unless `ENVIRONMENT` (default `$SENDPROOF_ENVIRONMENT`,
27
+ else `Production`) is in `ENVIRONMENTS` (default `["Development"]`).
28
+
29
+ ## Marking operations
30
+
31
+ ```python
32
+ from sendproof_django import preview
33
+
34
+ @preview(methods=["POST"]) # function view: methods accepted for previews
35
+ def create_item(request): ...
36
+
37
+ class Things(APIView): # Django REST framework (or any class-based view)
38
+ @preview # decorate the handler method
39
+ def post(self, request): ...
40
+
41
+ @api.post("/items") # Django Ninja: below the route decorator
42
+ @preview
43
+ def create_item(request, payload: ItemIn): ...
44
+ ```
45
+
46
+ Only marked operations are advertised and accepted. Without `methods`, a function view accepts
47
+ `POST`, `PUT`, `PATCH` and `DELETE`. Class-based handlers and Ninja operations use their own HTTP
48
+ methods. Routes written with `re_path` have no portable OpenAPI template and are not advertised.
49
+
50
+ ## Settings
51
+
52
+ | Key | Meaning |
53
+ | --- | --- |
54
+ | `PROVIDER` | `DjangoOrmPreview(using=("default",), database="label")`, an instance or dotted path. Without one, nothing is advertised and previews answer 503. |
55
+ | `IDENTITY` | `(request) -> Identity \| None` (callable or dotted path). Defaults to `request.user` when authenticated (subject = primary key). |
56
+ | `AUTHORIZE` | `(request, identity) -> bool`. Optional workbench policy (401/403). |
57
+ | `ENVIRONMENT`, `ENVIRONMENTS` | Where the workbench is on. |
58
+ | `API_NAME`, `OPENAPI_URL`, `DOCUMENTS`, `AUTH_PROVIDERS`, `FIELD_MODULES` | Discovery. `OPENAPI_URL` defaults to `/openapi.json`. |
59
+ | `INCLUDE_SQL_PARAMETER_VALUES` | Show SQL values (Development only by default). |
60
+ | `TRACE_TTL` | Seconds a trace is kept (default 300). |
61
+
62
+ Unknown keys raise `ValueError` so typos are not silently ignored.
63
+
64
+ ## How it works
65
+
66
+ A request to `/sendproof/_preview/<path>` with exactly `Prefer: tx=rollback` is resolved with your
67
+ URLconf, then a copy of the request is sent through the complete `MIDDLEWARE` chain and the real
68
+ view, in-process, with `transaction.atomic()` open on every enrolled database. Every middleware,
69
+ including path-based ones, sees the target path, and session changes stay on the copy, so they are
70
+ neither saved by the outer `SessionMiddleware` nor sent as a cookie. Sendproof checks again, last
71
+ in the chain, that the request still resolves to the marked view and method. The response is buffered (1 MiB cap),
72
+ the atomic blocks are rolled back and confirmed, and only then does the middleware answer with the
73
+ envelope. `Prefer: trace` on the original URL commits normally and adds `X-Sendproof-Trace`; the
74
+ same caller can fetch it from `/sendproof/_api/traces/{id}` until it expires.
75
+
76
+ - Commit semantics follow Django: a nested `atomic()` releases a savepoint, `transaction.on_commit`
77
+ callbacks are discarded with the rollback, and a handler that handles an `IntegrityError`
78
+ behaves as usual.
79
+ - A 401 or 403 is always a denial and never an envelope. Other statuses, including 409 and the
80
+ 400 or 422 your framework returns for invalid input, are the application's answer. An unhandled
81
+ exception becomes an unconfirmed 500.
82
+ - CSRF protection runs against the target view exactly as for a normal request. Sendproof
83
+ sends no CSRF token, so previews of views protected by it are rejected unless the view is
84
+ exempt or authenticates another way, as API views usually do.
85
+ - Mounted under a prefix (`SCRIPT_NAME`/`FORCE_SCRIPT_NAME`), discovery URLs include it. Django
86
+ Ninja prefixes OpenAPI paths with the script prefix; serve its schema with
87
+ `api.get_openapi_schema(path_prefix="/")` so the paths match the operations the workbench lists.
88
+
89
+ ## Change capture and coverage
90
+
91
+ Changes come from `pre_save`/`post_save`/`pre_delete`/`post_delete`: inserts, updates and deletes made
92
+ with `Model.save()`, `Model.objects.create()` and `Model.delete()`, including cascades the ORM
93
+ performs. The row before an update or delete is read from the database; that read is not logged.
94
+
95
+ - **Not captured (but rolled back):** `QuerySet.update()`, `bulk_create()`, `bulk_update()`, raw SQL,
96
+ triggers and cascades done by the database. Their SQL appears in the logs. Rows are never
97
+ synthesized.
98
+ - **Transaction-control SQL is refused before it is sent** and the Preview answers 500: `COMMIT`,
99
+ `ROLLBACK` (not `ROLLBACK TO SAVEPOINT`), `BEGIN`, `SET autocommit`, the internal
100
+ `sendproof_preview` savepoint, and on MySQL, MariaDB and Oracle the statements those databases
101
+ commit implicitly (DDL other than `TEMPORARY` tables, `LOCK TABLES`, `GRANT` and the rest of
102
+ MySQL's list). On MySQL and MariaDB `CALL` is refused too, because a procedure can commit,
103
+ unless you declare it safe by exact name (case-insensitive, no wildcards; the binding trusts the
104
+ declaration):
105
+
106
+ ```python
107
+ SENDPROOF = {"PROVIDER": lambda: DjangoOrmPreview(safe_procedures=["refresh_totals"]), ...}
108
+ ```
109
+
110
+ - **Backstop on every database:** the Preview opens its transaction with
111
+ `SAVEPOINT sendproof_preview` and checks, before rolling back, that it still exists. Any commit
112
+ erases it, so a Preview whose transaction was committed anyway (on the driver's own connection,
113
+ say, which then begins a new transaction) answers 500 without confirmation (the writes before
114
+ that commit stay).
115
+ - **Deadlocks on MySQL and MariaDB:** a deadlock (1213), or a lock wait timeout (1205) with
116
+ `innodb_rollback_on_timeout` on, rolls back the whole Preview transaction. The handler still gets
117
+ the original error; every later statement in that Preview except Django's own savepoint
118
+ rollbacks is refused before it is sent, and the Preview answers 500 without confirmation. The
119
+ lock wait timeout case shares the deadlock code path and is covered by unit tests only, because
120
+ `innodb_rollback_on_timeout` can be set only at server startup.
121
+ - Enrolled aliases share the request thread's connection. Work in other threads, other databases
122
+ you did not list, caches, files and other services are not rolled back.
123
+ - Synchronous views only. Async views and ASGI deployments are not tested.
124
+ - The inner response object is not closed during a preview, so Django's `request_finished`
125
+ connection cleanup cannot end the transaction early.
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "sendproof-django"
7
+ version = "0.1.0a2"
8
+ description = "Sendproof workbench, rollback previews and observed sends for Django, Django REST framework and Django Ninja, with Django ORM capture."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Sendproof contributors" }]
14
+ keywords = ["swagger", "api-testing", "django", "django-ninja", "djangorestframework", "openapi", "testing", "rollback"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Framework :: Django",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Programming Language :: Python :: 3 :: Only",
27
+ "Topic :: Software Development :: Testing",
28
+ "Typing :: Typed",
29
+ ]
30
+ dependencies = ["sendproof-core==0.1.0a2", "django>=4.2"]
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/sendproof_django"]
34
+
35
+ [tool.hatch.build.targets.sdist]
36
+ include = ["src/sendproof_django", "README.md", "LICENSE"]
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/mprync/sendproof/tree/main/adapters/python/django"
40
+ Repository = "https://github.com/mprync/sendproof"
41
+ Issues = "https://github.com/mprync/sendproof/issues"
42
+ Changelog = "https://github.com/mprync/sendproof/blob/main/CHANGELOG.md"
@@ -0,0 +1,46 @@
1
+ """Sendproof workbench, rollback previews and observed sends for Django."""
2
+
3
+ from sendproof_core import AuthProvider, Identity
4
+ from sendproof_core.marker import apply_marker
5
+
6
+ from .orm import DjangoOrmPreview
7
+
8
+ __all__ = ["AuthProvider", "DjangoOrmPreview", "Identity", "close_sessions", "preview"]
9
+ __version__ = "0.1.0a2"
10
+
11
+
12
+ def close_sessions() -> None:
13
+ """Roll back held Preview sessions during worker shutdown."""
14
+ from .conf import get_bench
15
+
16
+ get_bench().engine.sessions.close()
17
+
18
+
19
+ def preview(view=True, *, methods=None, reason=None, stores=None):
20
+ """Mark a view, or a handler method of a class-based view, as eligible for previews.
21
+
22
+ A function view lists the methods it accepts for previews (default: the write methods
23
+ ``POST``, ``PUT``, ``PATCH``, ``DELETE``)::
24
+
25
+ @preview(methods=["POST"])
26
+ def create_item(request): ...
27
+
28
+ On a class-based view, DRF ``APIView``/``ViewSet`` or Django Ninja operation, decorate the
29
+ handler (``post``, ``create``, the Ninja function) directly, below the route decorator::
30
+
31
+ @api.post("/items")
32
+ @preview
33
+ def create_item(request, payload: ItemIn): ...
34
+
35
+ An operation you know writes to a store a Preview cannot roll back, such as one that clears a
36
+ Redis session, can be marked ``preview: false``. The workbench then shows "Preview
37
+ unavailable" with your reason before anyone tries, a Preview of it is refused (never
38
+ confirmed) without running the view, and Send still runs it::
39
+
40
+ @preview(False, methods=["DELETE"], reason="Clears the Redis session", stores=["redis"])
41
+ def delete_session(request, id): ...
42
+
43
+ Without ``reason`` the published reason names the first of ``stores``. The binding never
44
+ infers the mark: without it the operation is advertised and the write guard decides at run time.
45
+ """
46
+ return apply_marker(view, True, reason=reason, stores=stores, methods=methods)
@@ -0,0 +1,100 @@
1
+ """Builds the Sendproof engine from ``settings.SENDPROOF``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from typing import Any, Callable
7
+
8
+ from django.conf import settings
9
+ from django.utils.module_loading import import_string
10
+
11
+ from sendproof_core import AuthProvider, BenchOptions, Identity, OpenApiDocument
12
+ from sendproof_core.stores.base import DataStore, StoresOnlyProvider, validate_stores
13
+ from sendproof_core.sync_engine import SyncBench
14
+ from sendproof_core.workbench import Workbench
15
+
16
+ _lock = threading.Lock()
17
+ _bench: "DjangoBench | None" = None
18
+
19
+ KEYS = {
20
+ "API_NAME", "OPENAPI_URL", "DOCUMENTS", "ENVIRONMENT", "ENVIRONMENTS", "PROVIDER", "IDENTITY",
21
+ "AUTHORIZE", "AUTH_PROVIDERS", "FIELD_MODULES", "INCLUDE_SQL_PARAMETER_VALUES", "TRACE_TTL", "DATA_STORES",
22
+ "JOURNEY_FILES", "JOURNEYS", "JOURNEY_OPENAPI", "SESSION_IDLE_TIMEOUT", "SESSION_MAX_LIFETIME",
23
+ }
24
+
25
+
26
+ def default_identity(request: Any) -> Identity | None:
27
+ """Identity of ``request.user`` when Django authentication has established one."""
28
+ user = getattr(request, "user", None)
29
+ if user is None or not user.is_authenticated:
30
+ return None
31
+ name = user.get_full_name() or user.get_username()
32
+ return Identity(name, None, str(user.pk), "django")
33
+
34
+
35
+ def _resolve(value: Any) -> Any:
36
+ return import_string(value) if isinstance(value, str) else value
37
+
38
+
39
+ class DjangoBench:
40
+ """The configured engine plus the hooks supplied in settings."""
41
+
42
+ def __init__(self, config: dict[str, Any]) -> None:
43
+ unknown = set(config) - KEYS
44
+ if unknown:
45
+ raise ValueError(f"Unknown SENDPROOF setting(s): {', '.join(sorted(unknown))}")
46
+ provider = _resolve(config.get("PROVIDER"))
47
+ if callable(provider) and not hasattr(provider, "begin"):
48
+ provider = provider()
49
+ stores = []
50
+ for entry in config.get("DATA_STORES", ()):
51
+ store = _resolve(entry)
52
+ stores.append(store() if callable(store) and not isinstance(store, DataStore) else store)
53
+ stores = validate_stores(stores)
54
+ # Without a SQL provider, hooked stores alone can carry a Preview (see sendproof_fastapi).
55
+ if provider is None and stores:
56
+ provider = StoresOnlyProvider()
57
+ self.identity: Callable[[Any], Identity | None] = _resolve(config.get("IDENTITY")) or default_identity
58
+ authorize = _resolve(config.get("AUTHORIZE"))
59
+ providers = [
60
+ p if isinstance(p, AuthProvider) else AuthProvider(p["label"], p["kind"], p.get("url"))
61
+ for p in config.get("AUTH_PROVIDERS", [])
62
+ ]
63
+ documents = [
64
+ d if isinstance(d, OpenApiDocument) else OpenApiDocument(d["name"], d["url"])
65
+ for d in config.get("DOCUMENTS", [])
66
+ ]
67
+ self.options = BenchOptions(
68
+ api_name=config.get("API_NAME"), openapi_url=config.get("OPENAPI_URL"), documents=documents,
69
+ environment=config.get("ENVIRONMENT"), environments=tuple(config.get("ENVIRONMENTS", ("Development",))),
70
+ auth_providers=providers, field_modules=list(config.get("FIELD_MODULES", [])),
71
+ include_sql_parameter_values=config.get("INCLUDE_SQL_PARAMETER_VALUES"),
72
+ trace_ttl=float(config.get("TRACE_TTL", 300.0)), identity=self.identity, framework="Django",
73
+ journey_files=tuple(config.get("JOURNEY_FILES", ())),
74
+ session_idle_timeout=config.get("SESSION_IDLE_TIMEOUT", 300),
75
+ session_max_lifetime=config.get("SESSION_MAX_LIFETIME", 1800),
76
+ journeys=tuple(config.get("JOURNEYS", ())),
77
+ )
78
+ self.provider = provider
79
+ schema_factory = config.get("JOURNEY_OPENAPI")
80
+ openapi = (lambda: import_string(schema_factory)()) if isinstance(schema_factory, str) else schema_factory
81
+ self.workbench = Workbench(self.options, provider, journey_openapi=openapi)
82
+ self.engine = SyncBench(self.options, provider, self.workbench, authorize, stores)
83
+
84
+
85
+ def get_bench() -> DjangoBench:
86
+ """The process-wide engine, built on first use from ``settings.SENDPROOF``."""
87
+ global _bench
88
+ with _lock:
89
+ if _bench is None:
90
+ _bench = DjangoBench(dict(getattr(settings, "SENDPROOF", {})))
91
+ return _bench
92
+
93
+
94
+ def reset() -> None:
95
+ """Forget the cached engine (tests)."""
96
+ global _bench
97
+ with _lock:
98
+ if _bench is not None:
99
+ _bench.engine.sessions.close()
100
+ _bench = None
@@ -0,0 +1,117 @@
1
+ """Finds previewable operations in a Django URLconf.
2
+
3
+ Three kinds of views are understood:
4
+
5
+ * plain function views decorated with :func:`sendproof_django.preview`;
6
+ * class-based views and Django REST framework views or viewsets whose handler methods
7
+ (``post``, ``create``...) are decorated;
8
+ * Django Ninja operations, whose handler functions are decorated.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from typing import Any, Iterable, Iterator
15
+
16
+ from django.urls import URLPattern, URLResolver
17
+ from django.urls.resolvers import RoutePattern
18
+
19
+ from sendproof_core.marker import is_marked, is_previewable, marked_methods, unavailable_info
20
+
21
+ _CONVERTER = re.compile(r"<(?:[^:<>]+:)?([^<>]+)>")
22
+ _HTTP_METHODS = ("get", "post", "put", "patch", "delete")
23
+
24
+
25
+ def _ninja_operations(callback: Any) -> Any:
26
+ """The operations of a Django Ninja path view, found on the bound view or in its closure."""
27
+ owners = [getattr(callback, "__self__", None)]
28
+ for cell in getattr(callback, "__closure__", None) or ():
29
+ try:
30
+ owners.append(cell.cell_contents)
31
+ except ValueError: # an empty cell
32
+ continue
33
+ for owner in owners:
34
+ operations = getattr(owner, "operations", None)
35
+ if isinstance(operations, (list, tuple)):
36
+ return operations
37
+ return None
38
+
39
+
40
+ def view_methods(callback: Any, *, unavailable: bool = False, observed: bool = False) -> set[str]:
41
+ """HTTP methods for which ``callback`` has a handler a Preview may run.
42
+
43
+ With ``unavailable`` true, the methods whose handler is marked ``preview: false`` instead;
44
+ with ``observed`` true, every marked handler, since an observed Send may trace both.
45
+ """
46
+ def wanted(handler: Any) -> bool:
47
+ if observed:
48
+ return is_marked(handler)
49
+ return (unavailable_info(handler) is not None) if unavailable else is_previewable(handler)
50
+
51
+ methods: set[str] = set()
52
+ operations = _ninja_operations(callback)
53
+ if operations is not None: # Django Ninja path view
54
+ for operation in operations:
55
+ if wanted(getattr(operation, "view_func", None)):
56
+ methods.update(m.upper() for m in operation.methods)
57
+ return methods
58
+ cls = getattr(callback, "view_class", None) or getattr(callback, "cls", None)
59
+ if cls is not None:
60
+ actions = getattr(callback, "actions", None) # DRF viewset: {"post": "create"}
61
+ for method in _HTTP_METHODS:
62
+ name = actions.get(method) if actions is not None else method
63
+ if name and wanted(getattr(cls, name, None)):
64
+ methods.add(method.upper())
65
+ return methods
66
+ if wanted(callback):
67
+ methods.update(marked_methods(callback))
68
+ return methods
69
+
70
+
71
+ def _walk(patterns: Iterable[Any], prefix: str) -> Iterator[tuple[str, Any]]:
72
+ for entry in patterns:
73
+ if not isinstance(entry.pattern, RoutePattern):
74
+ continue # regex routes have no portable OpenAPI template
75
+ route = prefix + str(entry.pattern)
76
+ if isinstance(entry, URLResolver):
77
+ yield from _walk(entry.url_patterns, route)
78
+ elif isinstance(entry, URLPattern):
79
+ yield route, entry.callback
80
+
81
+
82
+ def _reason(callback: Any) -> Any:
83
+ """The ``preview: false`` mark of the first handler of ``callback`` that has one."""
84
+ operations = _ninja_operations(callback)
85
+ if operations is not None:
86
+ handlers = [getattr(operation, "view_func", None) for operation in operations]
87
+ else:
88
+ cls = getattr(callback, "view_class", None) or getattr(callback, "cls", None)
89
+ actions = getattr(callback, "actions", None)
90
+ handlers = (
91
+ [getattr(cls, (actions.get(m) if actions is not None else m) or "", None) for m in _HTTP_METHODS]
92
+ if cls is not None else [callback]
93
+ )
94
+ return next((info for info in map(unavailable_info, handlers) if info is not None), None)
95
+
96
+
97
+ def unavailable_operations(patterns: Iterable[Any]) -> list[tuple[str, str, str, tuple[str, ...]]]:
98
+ """Method, path, reason and stores of every operation marked ``preview: false``."""
99
+ found = []
100
+ for route, callback in _walk(patterns, ""):
101
+ methods = view_methods(callback, unavailable=True)
102
+ marked = _reason(callback) if methods else None
103
+ if marked is not None:
104
+ path = "/" + _CONVERTER.sub(r"{\1}", route).lstrip("/")
105
+ found.extend((method, path, marked.reason, marked.stores) for method in sorted(methods))
106
+ return found
107
+
108
+
109
+ def preview_operations(patterns: Iterable[Any]) -> list[tuple[str, str]]:
110
+ """Method and OpenAPI path template of every operation a Preview may run."""
111
+ found = []
112
+ for route, callback in _walk(patterns, ""):
113
+ methods = view_methods(callback)
114
+ if methods:
115
+ path = "/" + _CONVERTER.sub(r"{\1}", route).lstrip("/")
116
+ found.extend((method, path) for method in sorted(methods))
117
+ return found