rn-forge-fastapi 0.4.0__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.
- rn_forge/fastapi/__init__.py +111 -0
- rn_forge/fastapi/app.py +210 -0
- rn_forge/fastapi/auth/__init__.py +69 -0
- rn_forge/fastapi/auth/authorization.py +62 -0
- rn_forge/fastapi/auth/csrf.py +243 -0
- rn_forge/fastapi/auth/dependencies.py +374 -0
- rn_forge/fastapi/auth/proxies.py +55 -0
- rn_forge/fastapi/auth/rate_limit.py +91 -0
- rn_forge/fastapi/auth/redis.py +88 -0
- rn_forge/fastapi/auth/routes.py +725 -0
- rn_forge/fastapi/auth/sessions.py +504 -0
- rn_forge/fastapi/cors.py +80 -0
- rn_forge/fastapi/dependencies.py +157 -0
- rn_forge/fastapi/deprecation.py +45 -0
- rn_forge/fastapi/health.py +71 -0
- rn_forge/fastapi/idempotency.py +82 -0
- rn_forge/fastapi/merge_patch.py +89 -0
- rn_forge/fastapi/openapi.py +91 -0
- rn_forge/fastapi/problem.py +155 -0
- rn_forge/fastapi/py.typed +0 -0
- rn_forge/fastapi/read_mask.py +86 -0
- rn_forge/fastapi/soft_delete.py +188 -0
- rn_forge/fastapi/transfer.py +936 -0
- rn_forge_fastapi-0.4.0.dist-info/METADATA +165 -0
- rn_forge_fastapi-0.4.0.dist-info/RECORD +27 -0
- rn_forge_fastapi-0.4.0.dist-info/WHEEL +4 -0
- rn_forge_fastapi-0.4.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""FastAPI dependency and helper for the ``readMask`` query parameter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import types
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from collections.abc import Set as AbstractSet
|
|
8
|
+
from typing import Annotated, Any, Union, cast, get_args, get_origin
|
|
9
|
+
|
|
10
|
+
from fastapi import Query
|
|
11
|
+
from pydantic import BaseModel
|
|
12
|
+
from rn_forge.web import READ_MASK_PARAM, FieldTree, Page, ReadMask, parse_read_mask
|
|
13
|
+
|
|
14
|
+
__all__ = ["masked", "read_mask_param"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def read_mask_param(model: type[BaseModel]) -> Callable[..., ReadMask | None]:
|
|
18
|
+
"""Return a dependency yielding the parsed ``readMask``, or ``None`` for the whole resource.
|
|
19
|
+
|
|
20
|
+
The declared fields are *model*'s serialization aliases, including its
|
|
21
|
+
computed fields. A field typed as a model, ``Model | None`` or ``list[Model]``
|
|
22
|
+
is a nested object whose own fields can be selected; any other field,
|
|
23
|
+
including a ``dict``, is a leaf. A path that names no declared field, or
|
|
24
|
+
that combines ``*`` with other paths, is a 400 before the route runs.
|
|
25
|
+
|
|
26
|
+
Apply the result with ``mask.apply(body)`` to a dumped resource, or with
|
|
27
|
+
:func:`masked` to a page.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
model: The model of one resource, as the route serves it.
|
|
31
|
+
"""
|
|
32
|
+
fields = _field_tree(model, frozenset())
|
|
33
|
+
|
|
34
|
+
def dependency(
|
|
35
|
+
read_mask: str | None = Query(
|
|
36
|
+
default=None,
|
|
37
|
+
alias=READ_MASK_PARAM,
|
|
38
|
+
description=(
|
|
39
|
+
"Comma-separated field paths to return, such as "
|
|
40
|
+
"`displayName,address.city`. `*` returns the whole resource."
|
|
41
|
+
),
|
|
42
|
+
),
|
|
43
|
+
) -> ReadMask | None:
|
|
44
|
+
return parse_read_mask(read_mask, fields=fields)
|
|
45
|
+
|
|
46
|
+
return dependency
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def masked(page: Page[Any], mask: ReadMask | None) -> dict[str, Any]:
|
|
50
|
+
"""Return the wire body of *page* with *mask* applied to each of its items.
|
|
51
|
+
|
|
52
|
+
``nextPageToken`` and ``totalSize`` are left alone. With no mask the body is
|
|
53
|
+
the page's own.
|
|
54
|
+
"""
|
|
55
|
+
body = page.as_body()
|
|
56
|
+
if mask is None:
|
|
57
|
+
return body
|
|
58
|
+
items = cast("list[Any]", body["items"])
|
|
59
|
+
return {**body, "items": [mask.apply(item) for item in items]}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _field_tree(model: type[BaseModel], path: frozenset[type]) -> FieldTree:
|
|
63
|
+
tree: dict[str, FieldTree | None] = {}
|
|
64
|
+
for name, info in model.model_fields.items():
|
|
65
|
+
key = info.serialization_alias or info.alias or name
|
|
66
|
+
tree[key] = _nested(info.annotation, path | {model})
|
|
67
|
+
for name, computed in model.model_computed_fields.items():
|
|
68
|
+
tree[computed.alias or name] = None
|
|
69
|
+
return tree
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _nested(annotation: Any, path: frozenset[type]) -> FieldTree | None:
|
|
73
|
+
"""The fields of the model *annotation* holds, directly or in a list or optional; else ``None``."""
|
|
74
|
+
if isinstance(annotation, type) and issubclass(annotation, BaseModel):
|
|
75
|
+
# A model that contains itself has no finite tree, so it stops at a leaf.
|
|
76
|
+
return None if annotation in path else _field_tree(annotation, path)
|
|
77
|
+
origin = get_origin(annotation)
|
|
78
|
+
args: tuple[Any, ...] = get_args(annotation)
|
|
79
|
+
if origin is Annotated:
|
|
80
|
+
return _nested(args[0], path)
|
|
81
|
+
if origin in (Union, types.UnionType):
|
|
82
|
+
present = [arg for arg in args if arg is not type(None)]
|
|
83
|
+
return _nested(present[0], path) if len(present) == 1 else None
|
|
84
|
+
if isinstance(origin, type) and issubclass(origin, (Sequence, AbstractSet)):
|
|
85
|
+
return _nested(args[0], path) if args else None
|
|
86
|
+
return None
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Soft delete over FastAPI (AIP-164): ``DELETE`` and ``:undelete`` routes and ``showDeleted``.
|
|
2
|
+
|
|
3
|
+
Persistence is the application's: :func:`soft_delete_router` takes a store
|
|
4
|
+
dependency that implements :class:`SoftDeleteStore`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Callable, Sequence
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from typing import Any, Protocol
|
|
11
|
+
|
|
12
|
+
from fastapi import APIRouter, Depends, Header, Query, Response
|
|
13
|
+
from fastapi.params import Depends as DependsParam
|
|
14
|
+
from pydantic import BaseModel
|
|
15
|
+
from rn_forge.fastapi.openapi import operation_id
|
|
16
|
+
from rn_forge.web import (
|
|
17
|
+
SHOW_DELETED_PARAM,
|
|
18
|
+
ETagCodec,
|
|
19
|
+
ResourceNotDeleted,
|
|
20
|
+
VersionETagCodec,
|
|
21
|
+
check_precondition,
|
|
22
|
+
parse_flag,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"SoftDeleteState",
|
|
27
|
+
"SoftDeleteStore",
|
|
28
|
+
"show_deleted_param",
|
|
29
|
+
"soft_delete_router",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class SoftDeleteState:
|
|
35
|
+
"""A row as :class:`SoftDeleteStore` reports it.
|
|
36
|
+
|
|
37
|
+
Attributes:
|
|
38
|
+
row: The stored row.
|
|
39
|
+
version: The row's version, or ``None`` when the resource is unversioned.
|
|
40
|
+
delete_time: When the row was soft-deleted; ``None`` while it is live.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
row: Any
|
|
44
|
+
version: int | None
|
|
45
|
+
delete_time: datetime | None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class SoftDeleteStore(Protocol):
|
|
49
|
+
"""Finds, soft-deletes and restores one resource.
|
|
50
|
+
|
|
51
|
+
The store owns the transaction and supplies the time recorded as
|
|
52
|
+
``delete_time``.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
async def find(self, id: str) -> SoftDeleteState | None:
|
|
56
|
+
"""Return the row with *id*, deleted or not, or ``None`` when it does not exist."""
|
|
57
|
+
...
|
|
58
|
+
|
|
59
|
+
async def soft_delete(self, id: str) -> Any:
|
|
60
|
+
"""Soft-delete the row and return it."""
|
|
61
|
+
...
|
|
62
|
+
|
|
63
|
+
async def undelete(self, id: str) -> Any:
|
|
64
|
+
"""Restore the row and return it."""
|
|
65
|
+
...
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def show_deleted_param() -> Callable[..., bool]:
|
|
69
|
+
"""Return a dependency yielding whether the request includes soft-deleted resources.
|
|
70
|
+
|
|
71
|
+
``showDeleted`` is ``true`` or ``1`` (any case) to include them; any other
|
|
72
|
+
value, or none, excludes them.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def dependency(
|
|
76
|
+
show_deleted: str | None = Query(
|
|
77
|
+
default=None,
|
|
78
|
+
alias=SHOW_DELETED_PARAM,
|
|
79
|
+
description="Include soft-deleted resources when `true` or `1`.",
|
|
80
|
+
),
|
|
81
|
+
) -> bool:
|
|
82
|
+
return parse_flag(show_deleted)
|
|
83
|
+
|
|
84
|
+
return dependency
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def soft_delete_router(
|
|
88
|
+
collection: str,
|
|
89
|
+
*,
|
|
90
|
+
response_model: type[BaseModel],
|
|
91
|
+
resource_label: str,
|
|
92
|
+
store: Callable[..., SoftDeleteStore],
|
|
93
|
+
require_if_match: bool = False,
|
|
94
|
+
codec: ETagCodec | None = None,
|
|
95
|
+
dependencies: Sequence[DependsParam] = (),
|
|
96
|
+
) -> APIRouter:
|
|
97
|
+
"""Build ``DELETE {collection}/{id}`` and ``POST {collection}/{id}:undelete``.
|
|
98
|
+
|
|
99
|
+
``DELETE`` soft-deletes and answers 200 with the resource, as
|
|
100
|
+
*response_model* dumped by alias. A missing or already deleted resource is a
|
|
101
|
+
404 reading ``{resource_label} {id} not found``. ``:undelete`` restores the
|
|
102
|
+
resource and answers 200 with it; a live resource is a 409 reading
|
|
103
|
+
``{resource_label} {id} is not deleted``.
|
|
104
|
+
|
|
105
|
+
On a versioned resource both honour ``If-Match`` after those checks (428,
|
|
106
|
+
400 or 412), and answer with the new ``ETag``. The store is not asked to
|
|
107
|
+
write after a failure.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
collection: The collection path, for example ``/notes``.
|
|
111
|
+
response_model: The model of one resource.
|
|
112
|
+
resource_label: The resource's name in problem details, for example ``Note``.
|
|
113
|
+
store: A dependency returning the :class:`SoftDeleteStore`.
|
|
114
|
+
require_if_match: When ``True``, a versioned request without
|
|
115
|
+
``If-Match`` is a 428.
|
|
116
|
+
codec: The validator format; ``None`` uses
|
|
117
|
+
:class:`rn_forge.web.VersionETagCodec`.
|
|
118
|
+
dependencies: Dependencies of the route, as for ``APIRouter``.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
The router.
|
|
122
|
+
"""
|
|
123
|
+
router = APIRouter(
|
|
124
|
+
dependencies=list(dependencies), generate_unique_id_function=operation_id
|
|
125
|
+
)
|
|
126
|
+
etag_codec = codec or VersionETagCodec()
|
|
127
|
+
|
|
128
|
+
def precondition(state: SoftDeleteState, id: str, if_match: str | None) -> None:
|
|
129
|
+
if state.version is not None:
|
|
130
|
+
check_precondition(
|
|
131
|
+
if_match,
|
|
132
|
+
current_version=state.version,
|
|
133
|
+
entity_id=id,
|
|
134
|
+
codec=etag_codec,
|
|
135
|
+
required=require_if_match,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
async def respond(
|
|
139
|
+
target: SoftDeleteStore, id: str, row: Any, response: Response
|
|
140
|
+
) -> dict[str, Any]:
|
|
141
|
+
after = await target.find(id)
|
|
142
|
+
if after is not None and after.version is not None:
|
|
143
|
+
response.headers["ETag"] = etag_codec.format(
|
|
144
|
+
entity_id=id, version=after.version
|
|
145
|
+
)
|
|
146
|
+
return response_model.model_validate(row, from_attributes=True).model_dump(
|
|
147
|
+
by_alias=True, mode="json"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
async def soft_delete(
|
|
151
|
+
id: str,
|
|
152
|
+
response: Response,
|
|
153
|
+
if_match: str | None = Header(default=None, alias="If-Match"),
|
|
154
|
+
target: SoftDeleteStore = Depends(store),
|
|
155
|
+
) -> dict[str, Any]:
|
|
156
|
+
state = await target.find(id)
|
|
157
|
+
if state is None or state.delete_time is not None:
|
|
158
|
+
raise LookupError(f"{resource_label} {id} not found")
|
|
159
|
+
precondition(state, id, if_match)
|
|
160
|
+
return await respond(target, id, await target.soft_delete(id), response)
|
|
161
|
+
|
|
162
|
+
async def undelete(
|
|
163
|
+
id: str,
|
|
164
|
+
response: Response,
|
|
165
|
+
if_match: str | None = Header(default=None, alias="If-Match"),
|
|
166
|
+
target: SoftDeleteStore = Depends(store),
|
|
167
|
+
) -> dict[str, Any]:
|
|
168
|
+
state = await target.find(id)
|
|
169
|
+
if state is None:
|
|
170
|
+
raise LookupError(f"{resource_label} {id} not found")
|
|
171
|
+
if state.delete_time is None:
|
|
172
|
+
raise ResourceNotDeleted(resource_label, id)
|
|
173
|
+
precondition(state, id, if_match)
|
|
174
|
+
return await respond(target, id, await target.undelete(id), response)
|
|
175
|
+
|
|
176
|
+
router.add_api_route(
|
|
177
|
+
f"{collection}/{{id}}",
|
|
178
|
+
soft_delete,
|
|
179
|
+
methods=["DELETE"],
|
|
180
|
+
response_model=response_model,
|
|
181
|
+
)
|
|
182
|
+
router.add_api_route(
|
|
183
|
+
f"{collection}/{{id}}:undelete",
|
|
184
|
+
undelete,
|
|
185
|
+
methods=["POST"],
|
|
186
|
+
response_model=response_model,
|
|
187
|
+
)
|
|
188
|
+
return router
|