sendproof-flask 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ """Sendproof workbench, rollback previews and observed sends for Flask."""
2
+
3
+ from sendproof_core import AuthProvider, Identity, OpenApiDocument
4
+
5
+ from .bench import Sendproof, preview
6
+
7
+ __all__ = ["AuthProvider", "Identity", "OpenApiDocument", "Sendproof", "preview"]
8
+ __version__ = "0.1.0a1"
@@ -0,0 +1,183 @@
1
+ """The public ``Sendproof`` object for Flask applications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import time
7
+ from typing import Any, Callable, Iterable, TypeVar
8
+
9
+ from flask import Flask, Request
10
+ from flask import got_request_exception
11
+ from werkzeug.routing import Rule
12
+
13
+ from sendproof_core import AuthProvider, BenchOptions, Identity, OpenApiDocument, PreviewProvider
14
+ from sendproof_core.assets import UiAssets
15
+ from sendproof_core.marker import apply_marker, is_previewable, marked_methods, unavailable_info
16
+ from sendproof_core.scope import current_scope, install_logging_capture
17
+ from sendproof_core.stores.base import DataStore, StoresOnlyProvider, validate_stores
18
+ from sendproof_core.sync_engine import SyncBench
19
+ from sendproof_core.workbench import Workbench
20
+
21
+ from .middleware import PREVIEW_VIEW, SendproofWsgi
22
+
23
+ F = TypeVar("F", bound=Callable[..., Any])
24
+ IdentityResolver = Callable[[Request], "Identity | None"]
25
+ Authorizer = Callable[[Request, "Identity | None"], bool]
26
+
27
+
28
+ def preview(
29
+ view: Any = True, *, reason: str | None = None, stores: Iterable[str] | None = None,
30
+ methods: Iterable[str] | None = None,
31
+ ) -> Any:
32
+ """Mark a Flask view function as eligible for Sendproof previews, or as ``preview: false``.
33
+
34
+ Apply it below the route decorator::
35
+
36
+ @app.post("/items")
37
+ @preview
38
+ def create_item(): ...
39
+
40
+ An operation you know writes to a store a Preview cannot roll back, such as one that clears a
41
+ Redis session, can be marked ``preview: false``. The workbench then shows "Preview
42
+ unavailable" with your reason before anyone tries, a Preview of it is refused (never
43
+ confirmed) without running the view, and Send still runs it::
44
+
45
+ @app.delete("/sessions/<id>")
46
+ @preview(False, reason="Clears the Redis session", stores=["redis"])
47
+ def delete_session(id): ...
48
+
49
+ Without ``reason`` the published reason names the first of ``stores``. The binding never
50
+ infers the mark: without it the operation is advertised and the write guard decides at run time.
51
+
52
+ A view is previewable for its write methods (``POST``, ``PUT``, ``PATCH``, ``DELETE``) unless
53
+ ``methods`` lists others, for example ``@preview(methods=["GET"])`` for a read that touches a store.
54
+ """
55
+ return apply_marker(view, True, reason=reason, stores=stores, methods=methods)
56
+
57
+
58
+ def _template(rule: Rule) -> str:
59
+ """Convert a Werkzeug rule (``/items/<int:id>``) to an OpenAPI path (``/items/{id}``)."""
60
+ return re.sub(r"<(?:[^:<>]+:)?([^<>]+)>", r"{\1}", rule.rule)
61
+
62
+
63
+ class Sendproof:
64
+ """Adds the Sendproof workbench to a Flask application.
65
+
66
+ The workbench is **off** unless ``environment`` is listed in ``environments`` (default
67
+ ``("Development",)``). ``environment`` defaults to ``$SENDPROOF_ENVIRONMENT`` and then to
68
+ ``"Production"``.
69
+
70
+ Args:
71
+ app: The Flask application. Create the ``Sendproof`` after registering your routes or
72
+ before; operations are discovered per request.
73
+ provider: A data-layer provider such as ``sendproof_sqlalchemy.SQLAlchemyPreview``.
74
+ data_stores: Hooked data stores (``mongo_store``, ``redis_store``, ``dynamodb_store`` from
75
+ ``sendproof_core.stores``). MongoDB rolls back in its own transaction, and Redis and
76
+ DynamoDB block a write during a Preview. They also let an app with no SQL ``provider``
77
+ Preview: a SQL database you give no provider for is then not covered. Only hooked
78
+ clients are covered. Use synchronous clients (PyMongo, redis-py, boto3).
79
+ identity: ``(request) -> Identity | None``. Runs inside a request context, so
80
+ ``flask.session`` and ``flask_login`` work. Used for discovery and to own traces.
81
+ authorize: Optional ``(request, identity) -> bool`` policy for the workbench.
82
+ api_name, openapi_url, documents, auth_providers, field_modules,
83
+ include_sql_parameter_values, trace_ttl, clock: See ``sendproof_fastapi.Sendproof``.
84
+ Flask has no built-in OpenAPI route; ``openapi_url`` defaults to ``/openapi.json``.
85
+ """
86
+
87
+ __test__ = False
88
+
89
+ def __init__(
90
+ self,
91
+ app: Flask,
92
+ *,
93
+ provider: PreviewProvider | None = None,
94
+ data_stores: Iterable[DataStore] = (),
95
+ identity: IdentityResolver | None = None,
96
+ authorize: Authorizer | None = None,
97
+ api_name: str | None = None,
98
+ openapi_url: str | None = None,
99
+ documents: Iterable[OpenApiDocument] = (),
100
+ environment: str | None = None,
101
+ environments: Iterable[str] = ("Development",),
102
+ auth_providers: Iterable[AuthProvider] = (),
103
+ field_modules: Iterable[str] = (),
104
+ include_sql_parameter_values: bool | None = None,
105
+ trace_ttl: float = 300.0,
106
+ clock: Callable[[], float] = time.monotonic,
107
+ assets: UiAssets | None = None,
108
+ ) -> None:
109
+ self.app = app
110
+ stores = validate_stores(data_stores)
111
+ # Without a SQL provider, hooked stores alone can carry a Preview (see sendproof_fastapi).
112
+ if provider is None and stores:
113
+ provider = StoresOnlyProvider()
114
+ self.provider = provider
115
+ self.options = BenchOptions(
116
+ api_name=api_name, openapi_url=openapi_url, documents=list(documents), environment=environment,
117
+ environments=tuple(environments), auth_providers=list(auth_providers), field_modules=list(field_modules),
118
+ include_sql_parameter_values=include_sql_parameter_values, trace_ttl=trace_ttl, clock=clock, identity=identity,
119
+ framework="Flask",
120
+ )
121
+ self.workbench = Workbench(self.options, provider, assets)
122
+ self.engine = SyncBench(self.options, provider, self.workbench, authorize, stores)
123
+ app.wsgi_app = SendproofWsgi(app.wsgi_app, self) # type: ignore[method-assign]
124
+ # First in line, so no host hook or view runs for a preview that no longer targets the
125
+ # marked view it was checked against.
126
+ app.before_request_funcs.setdefault(None, []).insert(0, self._verify_preview_target)
127
+ got_request_exception.connect(_remember_unhandled, app, weak=False)
128
+ install_logging_capture()
129
+
130
+ @property
131
+ def enabled(self) -> bool:
132
+ return self.options.enabled
133
+
134
+ def _verify_preview_target(self) -> Any:
135
+ """Last check of a re-dispatched preview, after every WSGI middleware has run.
136
+
137
+ Middleware may have changed the method (method override) or the path. Unless the request
138
+ still routes to the marked view and method checked earlier, nothing else runs and the
139
+ preview answers 409. Routing errors are left to Flask (404, 405).
140
+ """
141
+ from flask import request
142
+
143
+ expected = request.environ.get(PREVIEW_VIEW)
144
+ if expected is None or request.routing_exception is not None:
145
+ return None
146
+ view = self.app.view_functions.get(request.endpoint)
147
+ if view is expected and request.method in marked_methods(view):
148
+ return None
149
+ return self.app.response_class(
150
+ '{"status":409,"title":"This operation is unavailable for preview."}',
151
+ status=409, content_type="application/problem+json",
152
+ )
153
+
154
+ def operations(self) -> list[tuple[str, str]]:
155
+ """Method and OpenAPI path of every view a Preview may run."""
156
+ found = []
157
+ for rule in self.app.url_map.iter_rules():
158
+ view = self.app.view_functions.get(rule.endpoint)
159
+ if view is None or not is_previewable(view):
160
+ continue
161
+ allowed = set(marked_methods(view))
162
+ for method in sorted((rule.methods or set()) & allowed):
163
+ found.append((method, _template(rule)))
164
+ return found
165
+
166
+ def unavailable(self) -> list[tuple[str, str, str, tuple[str, ...]]]:
167
+ """Method, path, reason and stores of every view marked ``preview: false``."""
168
+ found = []
169
+ for rule in self.app.url_map.iter_rules():
170
+ marked = unavailable_info(self.app.view_functions.get(rule.endpoint))
171
+ if marked is None:
172
+ continue
173
+ allowed = set(marked_methods(self.app.view_functions[rule.endpoint]))
174
+ for method in sorted((rule.methods or set()) & allowed):
175
+ found.append((method, _template(rule), marked.reason, marked.stores))
176
+ return found
177
+
178
+
179
+ def _remember_unhandled(sender: Any, exception: BaseException, **extra: Any) -> None:
180
+ """Flask turns unhandled errors into 500 responses; remember them so a preview can fail."""
181
+ scope = current_scope()
182
+ if scope is not None:
183
+ scope.extensions["unhandled"] = exception
@@ -0,0 +1,279 @@
1
+ """WSGI middleware that serves the workbench and runs previews and observed sends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from typing import Any, Callable, Iterable
8
+
9
+ from werkzeug.datastructures import EnvironHeaders
10
+ from werkzeug.exceptions import HTTPException
11
+ from werkzeug.routing import RequestRedirect
12
+
13
+ from sendproof_core import Identity, limits, protocol
14
+ from sendproof_core.marker import is_marked, is_previewable, marked_methods
15
+ from sendproof_core.scope import enter_request, leave_request
16
+ from sendproof_core.sync_engine import Inner, ResponseTooLarge, is_application_response
17
+ from sendproof_core.workbench import Response, problem_response
18
+
19
+ logger = logging.getLogger("sendproof_flask")
20
+ StartResponse = Callable[..., Callable[[bytes], Any]]
21
+
22
+ #: WSGI environ key of a re-dispatched preview: the view checked before the handler runs.
23
+ #: Only this middleware sets it; HTTP clients can only add ``HTTP_*`` keys.
24
+ PREVIEW_VIEW = "sendproof.preview_view"
25
+
26
+
27
+ class SendproofWsgi:
28
+ """Intercepts ``/sendproof/*`` and Preview/Observed requests; everything else passes through."""
29
+
30
+ __test__ = False
31
+
32
+ def __init__(self, app: Callable[..., Iterable[bytes]], bench: Any) -> None:
33
+ self.app, self.bench = app, bench
34
+
35
+ def __call__(self, environ: dict, start_response: StartResponse) -> Iterable[bytes]:
36
+ # Every request is attributed, so a store write that no request accounts for (a thread a
37
+ # Preview handler started without its context) can fail the open Previews. The mark lasts
38
+ # until the server closes the body, so a streamed body is covered too.
39
+ token = enter_request()
40
+ try:
41
+ body = self._handle(environ, start_response)
42
+ except BaseException:
43
+ leave_request(token)
44
+ raise
45
+ return _RequestBody(body, token)
46
+
47
+ def _handle(self, environ: dict, start_response: StartResponse) -> Iterable[bytes]:
48
+ bench = self.bench
49
+ if not bench.options.enabled or PREVIEW_VIEW in environ:
50
+ # A re-dispatched preview passes straight through; Flask checks it in before_request.
51
+ return self.app(environ, start_response)
52
+ started = time.perf_counter()
53
+ path = environ.get("PATH_INFO", "") or "/"
54
+ headers = EnvironHeaders(environ)
55
+ engine = bench.engine
56
+ if engine.is_reserved(path):
57
+ if engine.is_preview_path(path):
58
+ return self._respond(start_response, self._preview(environ, headers, path, started), environ)
59
+ return self._respond(start_response, self._workbench(environ, headers, path), environ)
60
+ if protocol.requests_rollback(headers.getlist):
61
+ return self._respond(start_response, problem_response(400, "Use the Sendproof preview URL for rollback requests."), environ)
62
+ if environ["REQUEST_METHOD"] != "HEAD" and protocol.requests_trace(headers.getlist):
63
+ observed = self._observed(environ, headers, started)
64
+ if observed is not None:
65
+ return self._run_observed(observed, environ, start_response)
66
+ return self.app(environ, start_response)
67
+
68
+ # ------------------------------------------------------------------ helpers
69
+ @staticmethod
70
+ def _respond(start_response: StartResponse, response: Response, environ: dict) -> Iterable[bytes]:
71
+ head = environ["REQUEST_METHOD"] == "HEAD"
72
+ headers = [(k, v) for k, v in response.headers if k.lower() != "content-length"]
73
+ headers.append(("Content-Length", str(len(response.body))))
74
+ from http import HTTPStatus
75
+
76
+ try:
77
+ phrase = HTTPStatus(response.status).phrase
78
+ except ValueError:
79
+ phrase = "Status"
80
+ start_response(f"{response.status} {phrase}", headers)
81
+ return [b"" if head else response.body]
82
+
83
+ def _hook(self, environ: dict, call: Callable[[Any], Any]) -> Any:
84
+ """Run an identity or authorization hook inside a Flask request context."""
85
+ with self.bench.app.request_context(dict(environ)):
86
+ from flask import request
87
+
88
+ return call(request)
89
+
90
+ def _identity(self, environ: dict) -> Identity | None:
91
+ resolver = self.bench.options.identity
92
+ if resolver is None:
93
+ return None
94
+ try:
95
+ return self._hook(environ, resolver)
96
+ except Exception:
97
+ logger.exception("The Sendproof identity resolver failed; treating the caller as anonymous.")
98
+ return None
99
+
100
+ def _authorized(self, environ: dict, identity: Identity | None) -> bool:
101
+ hook = self.bench.engine.authorize
102
+ if hook is None:
103
+ return True
104
+ try:
105
+ return bool(self._hook(environ, lambda request: hook(request, identity)))
106
+ except Exception:
107
+ logger.exception("The Sendproof authorization hook failed; denying access.")
108
+ return False
109
+
110
+ @staticmethod
111
+ def _origin_ok(environ: dict, headers: EnvironHeaders) -> bool:
112
+ return protocol.is_same_origin(headers.getlist, environ.get("wsgi.url_scheme", "http"), headers.get("Host", ""))
113
+
114
+ def _match(self, environ: dict, path: str) -> tuple[Any, int | None]:
115
+ """Resolve ``path`` with Flask's own router: (view or None, failing status)."""
116
+ adapter = self.bench.app.url_map.bind_to_environ({**environ, "PATH_INFO": path})
117
+ try:
118
+ endpoint, _ = adapter.match(method=environ["REQUEST_METHOD"])
119
+ except RequestRedirect:
120
+ return None, 308
121
+ except HTTPException as error:
122
+ return None, error.code
123
+ return self.bench.app.view_functions.get(endpoint), None
124
+
125
+ # ---------------------------------------------------------------- workbench
126
+ def _workbench(self, environ: dict, headers: EnvironHeaders, path: str) -> Response:
127
+ bench = self.bench
128
+ identity = self._identity(environ)
129
+ return bench.engine.serve_workbench(
130
+ method=environ["REQUEST_METHOD"], path=path, path_base=environ.get("SCRIPT_NAME", ""),
131
+ query=environ.get("QUERY_STRING", ""), identity=identity, authorized=self._authorized(environ, identity),
132
+ origin_ok=self._origin_ok(environ, headers), operations=bench.operations,
133
+ default_openapi_url="/openapi.json", default_api_name=bench.app.name, unavailable=bench.unavailable,
134
+ )
135
+
136
+ # ------------------------------------------------------------------ preview
137
+ def _preview(self, environ: dict, headers: EnvironHeaders, path: str, started: float) -> Response:
138
+ bench, engine = self.bench, self.bench.engine
139
+ method = environ["REQUEST_METHOD"]
140
+ rejection = engine.check_preview_request(
141
+ method=method, path=path, get_header=headers.getlist, origin_ok=self._origin_ok(environ, headers)
142
+ )
143
+ if rejection is not None:
144
+ return rejection
145
+ target = path[len(protocol.PREVIEW_PREFIX):]
146
+ view, failure = self._match(environ, target)
147
+ if view is None:
148
+ return problem_response(404 if failure in (404, None) else 405 if failure == 405 else 404,
149
+ "The preview target was not found for this method.")
150
+ if not is_previewable(view) or method not in marked_methods(view):
151
+ return problem_response(409, "This operation is unavailable for preview.")
152
+ identity = self._identity(environ)
153
+ if not self._authorized(environ, identity):
154
+ return problem_response(403 if identity else 401, "This preview is forbidden.")
155
+
156
+ inner_env = dict(environ)
157
+ inner_env["PATH_INFO"] = target
158
+ inner_env.pop("HTTP_ACCEPT_ENCODING", None)
159
+ inner_env["HTTP_CACHE_CONTROL"] = "no-cache, no-store"
160
+ inner_env[PREVIEW_VIEW] = view
161
+
162
+ def dispatch(scope: Any) -> Inner:
163
+ captured: dict[str, Any] = {}
164
+
165
+ def start(status: str, response_headers: list[tuple[str, str]], exc_info: Any = None):
166
+ captured["status"] = int(status.split(" ", 1)[0])
167
+ captured["headers"] = list(response_headers)
168
+ return lambda data: None
169
+
170
+ chunks, size = [], 0
171
+ # Dispatch through the application's whole WSGI chain (``app.wsgi_app`` as it is now,
172
+ # including middleware wrapped around Sendproof later), so path-based host
173
+ # middleware sees the target path rather than /sendproof/_preview.
174
+ iterable = bench.app.wsgi_app(inner_env, start)
175
+ try:
176
+ for chunk in iterable:
177
+ size += len(chunk)
178
+ if size > limits.RESPONSE_BYTES:
179
+ raise ResponseTooLarge
180
+ chunks.append(chunk)
181
+ finally:
182
+ close = getattr(iterable, "close", None)
183
+ if close:
184
+ close()
185
+ unhandled = scope.extensions.get("unhandled")
186
+ if unhandled is not None:
187
+ raise unhandled
188
+ return Inner(captured["status"], captured["headers"], b"".join(chunks))
189
+
190
+ return engine.preview(dispatch=dispatch, started=started, method=method, path=path)
191
+
192
+ # ----------------------------------------------------------------- observed
193
+ def _observed(self, environ: dict, headers: EnvironHeaders, started: float):
194
+ bench = self.bench
195
+ if not bench.engine.provider_available or not self._origin_ok(environ, headers):
196
+ return None
197
+ view, failure = self._match(environ, environ.get("PATH_INFO", "/"))
198
+ if view is None or not is_marked(view) or environ["REQUEST_METHOD"] not in marked_methods(view):
199
+ return None
200
+ identity = self._identity(environ)
201
+ return bench.engine.begin_observed(
202
+ identity=identity, path_base=environ.get("SCRIPT_NAME", ""), started=started,
203
+ authorized=self._authorized(environ, identity),
204
+ )
205
+
206
+ def _run_observed(self, observed: Any, environ: dict, start_response: StartResponse) -> Iterable[bytes]:
207
+ state = {"started": False}
208
+
209
+ def start(status: str, response_headers: list[tuple[str, str]], exc_info: Any = None):
210
+ state["started"] = True
211
+ if is_application_response(observed.scope, int(status.split(" ", 1)[0])):
212
+ dropped = {"cache-control", "server-timing"}
213
+ response_headers = [(k, v) for k, v in response_headers if k.lower() not in dropped] + observed.headers()
214
+ return start_response(status, response_headers, exc_info)
215
+
216
+ try:
217
+ body = self.app(environ, start)
218
+ except BaseException:
219
+ observed.finish(False)
220
+ raise
221
+ return _ObservedBody(body, observed, state)
222
+
223
+
224
+ class _RequestBody:
225
+ """Keeps the request mark until the body is consumed or closed, whichever comes first."""
226
+
227
+ def __init__(self, body: Iterable[bytes], token: Any) -> None:
228
+ self._body, self._token = body, token
229
+
230
+ def __iter__(self):
231
+ try:
232
+ yield from self._body
233
+ finally:
234
+ self._leave()
235
+
236
+ def close(self) -> None:
237
+ try:
238
+ close = getattr(self._body, "close", None)
239
+ if close:
240
+ close()
241
+ finally:
242
+ self._leave()
243
+
244
+ def _leave(self) -> None:
245
+ token, self._token = self._token, None
246
+ if token is not None:
247
+ leave_request(token)
248
+
249
+
250
+ class _ObservedBody:
251
+ """Publishes the trace once the server has consumed the response body, or closed it, whichever comes first."""
252
+
253
+ def __init__(self, body: Iterable[bytes], observed: Any, state: dict) -> None:
254
+ self._body, self._observed, self._state, self._done = body, observed, state, False
255
+
256
+ def __iter__(self):
257
+ try:
258
+ yield from self._body
259
+ except BaseException:
260
+ self._finish(False)
261
+ raise
262
+ # The body is complete. Publish now rather than waiting for the server to call ``close``: a
263
+ # server that fails while it drains an abandoned connection (Werkzeug's development server,
264
+ # when the client resets the socket after cancelling the body) never reaches ``close``, and
265
+ # the trace would stay reserved until it expires.
266
+ self._finish(self._state["started"])
267
+
268
+ def close(self) -> None:
269
+ try:
270
+ close = getattr(self._body, "close", None)
271
+ if close:
272
+ close()
273
+ finally:
274
+ self._finish(self._state["started"])
275
+
276
+ def _finish(self, completed: bool) -> None:
277
+ if not self._done:
278
+ self._done = True
279
+ self._observed.finish(completed)
File without changes
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.4
2
+ Name: sendproof-flask
3
+ Version: 0.1.0a1
4
+ Summary: Sendproof workbench, rollback previews and observed sends for Flask applications.
5
+ Project-URL: Homepage, https://github.com/mprync/sendproof/tree/main/adapters/python/flask
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,flask,openapi,rollback,swagger,testing,wsgi
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: Flask
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: flask>=2.3
28
+ Requires-Dist: sendproof-core==0.1.0a1
29
+ Description-Content-Type: text/markdown
30
+
31
+ # sendproof-flask
32
+
33
+ Serves the [Sendproof](../../spec/README.md) workbench from a Flask application and runs
34
+ rollback **Preview** and **Observed Send** through Flask's own routing and your view code.
35
+
36
+ ```sh
37
+ pip install sendproof-flask sendproof-sqlalchemy
38
+ ```
39
+
40
+ ```python
41
+ from flask import Flask, session
42
+ from sendproof_flask import AuthProvider, Identity, Sendproof, preview
43
+ from sendproof_sqlalchemy import SQLAlchemyPreview
44
+
45
+ app = Flask(__name__)
46
+
47
+ def identity(request) -> Identity | None: # runs in a request context: flask.session works
48
+ user = session.get("user")
49
+ return user and Identity(user["name"], user["role"], subject=user["id"], authentication_type="session")
50
+
51
+ Sendproof(
52
+ app,
53
+ provider=SQLAlchemyPreview(engine, database="inventory_dev"),
54
+ identity=identity,
55
+ environment="Development", # off in any environment not listed
56
+ openapi_url="/openapi.json", # wherever you serve your OpenAPI document
57
+ auth_providers=[AuthProvider("Password", "cookie", "/auth/sign-in")],
58
+ )
59
+
60
+ @app.post("/items")
61
+ @preview # below the route decorator
62
+ def create_item(): ...
63
+ ```
64
+
65
+ Open `/sendproof/`. The workbench needs an OpenAPI document; Flask has none built in, so serve one
66
+ (for example with `apispec` or `flask-smorest`) and set `openapi_url`.
67
+
68
+ ## How it works
69
+
70
+ `Sendproof` wraps `app.wsgi_app`. A request to `/sendproof/_preview/<path>` with exactly
71
+ `Prefer: tx=rollback` is matched against the app's own URL map, executed in-process through the
72
+ current `app.wsgi_app` chain (so WSGI middleware wrapped around Sendproof later also sees the
73
+ target path), buffered (1 MiB cap), rolled back, and only then answered with the confirmed envelope.
74
+ A `before_request` hook that runs first checks again that the request still reaches the marked view
75
+ and method; a middleware that changed either gets a 409 and no view runs.
76
+ `Prefer: trace` on the original URL commits normally and adds `X-Sendproof-Trace` for a caller with
77
+ a stable `Identity.subject`; fetch it from `/sendproof/_api/traces/{id}` as the same caller within
78
+ `trace_ttl` seconds.
79
+
80
+ - Only `@preview` views are advertised and accepted, and only for their write methods
81
+ (`POST`, `PUT`, `PATCH`, `DELETE`) or the methods you pass with `@preview` on a view registered
82
+ for them.
83
+ - **Denials.** Flask has no dependency layer, so authentication usually happens inside the view.
84
+ A 401 or 403 response is therefore always treated as a denial and never returned as an
85
+ envelope. Any other status the view returns, including 409, is the application's answer and
86
+ appears inside the envelope. An unhandled exception becomes an unconfirmed 500.
87
+ - A `Request` is available to `identity` and `authorize` hooks; do not read the request body in
88
+ them.
89
+ - Record outgoing email and similar effects with `sendproof_core.record_email`, and skip delivery
90
+ when it returns `True`.
91
+
92
+ Options match [`sendproof-fastapi`](../fastapi/README.md#options).
93
+
94
+ ## Data layer
95
+
96
+ `sendproof-sqlalchemy` (sync engines). The provider enrolls the engine, so plain SQLAlchemy
97
+ sessions, `scoped_session`, Flask-SQLAlchemy's `db.session` and raw `engine.begin()` connections all
98
+ share the preview connection. See the [coverage notes](../sqlalchemy/README.md#coverage-notes). A
99
+ Flask development server runs requests on threads: with SQLite, previews at the same time block
100
+ each other.
101
+
102
+ ### Flask-SQLAlchemy
103
+
104
+ Pass the extension's engine to the provider. `db.engine` needs an application context, so read it
105
+ inside one:
106
+
107
+ ```python
108
+ from flask import Flask
109
+ from flask_sqlalchemy import SQLAlchemy
110
+ from sendproof_flask import Sendproof, preview
111
+ from sendproof_sqlalchemy import SQLAlchemyPreview
112
+
113
+ app = Flask(__name__)
114
+ app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql+psycopg://app:secret@localhost/inventory_dev"
115
+ db = SQLAlchemy(app)
116
+
117
+ with app.app_context():
118
+ engines = list(db.engines.values()) # the default engine plus every SQLALCHEMY_BINDS entry
119
+
120
+ Sendproof(app, provider=SQLAlchemyPreview(*engines, database="inventory_dev"),
121
+ identity=identity, environment="Development", openapi_url="/openapi.json")
122
+
123
+ @app.post("/items")
124
+ @preview
125
+ def create_item():
126
+ db.session.add(Item(**request.get_json()))
127
+ db.session.commit() # a real commit in normal use, a rolled-back one in Preview
128
+ return jsonify(id=...), 201
129
+ ```
130
+
131
+ Handlers need no changes. In a preview `db.session.commit()` ends the emulated transaction,
132
+ `db.session.rollback()` undoes only the work since the last commit, `begin_nested()` is a real
133
+ `SAVEPOINT`, and `after_commit` listeners still run. Record emails and other deliveries with
134
+ `record_email` and friends, which return `True` during a preview, so a listener that sends them is
135
+ suppressed. Flask-SQLAlchemy removes the scoped session when each request's application context ends,
136
+ which also happens for the in-process request a preview runs.
137
+
138
+ ### Verified and limits
139
+
140
+ Verified with Flask 3.1.3, Flask-SQLAlchemy 3.1.1 and SQLAlchemy 2.1.9, on SQLite, PostgreSQL 17
141
+ (psycopg 3.3.9) and MySQL 8.4 (PyMySQL 1.2.4). `adapters/python/conformance/fixture_flask_sqlalchemy.py`
142
+ passed all 11 shared HTTP checks on each, as did the plain-SQLAlchemy `fixture_flask.py`. The package
143
+ tests (`flask/tests`, 20 tests) cover the same lifecycle, transaction, commit-hook and authorization
144
+ cases on SQLite by default. To run them on another database, export `BENCH_DATABASE=postgresql` or
145
+ `mysql` and `BENCH_DATABASE_URL=<disposable database>`; the tests drop and recreate their `items` and
146
+ `audit` tables.
147
+
148
+ - **Enroll every engine.** A `SQLALCHEMY_BINDS` engine that is not passed to `SQLAlchemyPreview` is
149
+ not rolled back and its rows are not captured; its writes persist even in a preview. Pass
150
+ `db.engines.values()`.
151
+ - **Dialects.** Verified on SQLite, PostgreSQL and MySQL. The provider uses `SAVEPOINT`. MariaDB
152
+ and Oracle remain unverified. The provider reports SQL Server previews as unavailable.
153
+ An `AUTOCOMMIT` engine cannot be rolled back and previews are refused.
154
+ - **Not tested.** Flask-Login, Flask async views, Flask-Migrate and `AsyncEngine` under Flask.
155
+ - **Commit hooks run during a preview.** Code in `after_commit` that has side effects outside the
156
+ database must go through `record_*`, or it will deliver for real.
@@ -0,0 +1,8 @@
1
+ sendproof_flask/__init__.py,sha256=dodPJypDsTprej2uGVnTPUfmjqj14Nwm05U9jtFpSNY,289
2
+ sendproof_flask/bench.py,sha256=uP8exnY_GeqrbS_n9q_eDPxkr5tTREWWiPdVF9L_54E,8667
3
+ sendproof_flask/middleware.py,sha256=9x8ujqd5s2657aulVnlfs7DHk5UhRg4teSt_eEAl2u4,12632
4
+ sendproof_flask/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ sendproof_flask-0.1.0a1.dist-info/METADATA,sha256=YZe1pm3vtVw0-zjiB3ntS-k31KQeTSWubtUyDZFGtc4,7633
6
+ sendproof_flask-0.1.0a1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ sendproof_flask-0.1.0a1.dist-info/licenses/LICENSE,sha256=FN_kx0TTA_TvTWeb5MzY7v1r6PwKKhW5msNFB2MeWSs,1079
8
+ sendproof_flask-0.1.0a1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.