resource-engine-fastapi 0.1.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.
- resource_engine_fastapi/__init__.py +39 -0
- resource_engine_fastapi/access.py +110 -0
- resource_engine_fastapi/asyncapi.py +47 -0
- resource_engine_fastapi/auth.py +158 -0
- resource_engine_fastapi/authz.py +100 -0
- resource_engine_fastapi/caching.py +111 -0
- resource_engine_fastapi/docs.py +77 -0
- resource_engine_fastapi/documents.py +219 -0
- resource_engine_fastapi/email_events.py +85 -0
- resource_engine_fastapi/errors.py +178 -0
- resource_engine_fastapi/events.py +109 -0
- resource_engine_fastapi/explorer/__init__.py +441 -0
- resource_engine_fastapi/explorer/assets/auth.js +171 -0
- resource_engine_fastapi/explorer/assets/console.js +340 -0
- resource_engine_fastapi/explorer/assets/events.js +189 -0
- resource_engine_fastapi/explorer/assets/explorer.css +156 -0
- resource_engine_fastapi/explorer/assets/explorer.js +275 -0
- resource_engine_fastapi/explorer/assets/jobs.js +143 -0
- resource_engine_fastapi/explorer/assets/messages.js +85 -0
- resource_engine_fastapi/explorer/assets/publish.js +117 -0
- resource_engine_fastapi/explorer/data.py +84 -0
- resource_engine_fastapi/explorer/events.py +182 -0
- resource_engine_fastapi/explorer/jobs.py +167 -0
- resource_engine_fastapi/explorer/labels.py +198 -0
- resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.mo +0 -0
- resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.po +417 -0
- resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.mo +0 -0
- resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.po +417 -0
- resource_engine_fastapi/explorer/messages.py +73 -0
- resource_engine_fastapi/explorer/publish.py +85 -0
- resource_engine_fastapi/exports.py +186 -0
- resource_engine_fastapi/i18n.py +76 -0
- resource_engine_fastapi/py.typed +0 -0
- resource_engine_fastapi/router.py +1031 -0
- resource_engine_fastapi/versioning.py +49 -0
- resource_engine_fastapi-0.1.0.dist-info/METADATA +32 -0
- resource_engine_fastapi-0.1.0.dist-info/RECORD +39 -0
- resource_engine_fastapi-0.1.0.dist-info/WHEEL +4 -0
- resource_engine_fastapi-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Background exports and printouts over HTTP.
|
|
2
|
+
|
|
3
|
+
- ``POST /<resource>/exports`` (in the resource's router) queues an export.
|
|
4
|
+
- ``GET /exports/{id}``: its status; ``GET /exports/{id}/content``: the file
|
|
5
|
+
(or a 307 to a presigned URL with ``redirect_downloads``).
|
|
6
|
+
- ``GET /<resource>/{id}/printouts/<name>?format=pdf``: a document rendered
|
|
7
|
+
from the record (``Resource.printouts``), not stored.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import inspect
|
|
13
|
+
from typing import Any, Literal
|
|
14
|
+
|
|
15
|
+
from fastapi import APIRouter, Depends, Path, Query, Response
|
|
16
|
+
from fastapi.responses import RedirectResponse, StreamingResponse
|
|
17
|
+
from pydantic import BaseModel, Field
|
|
18
|
+
from resource_engine import ResourceDefinition, ResourceManager
|
|
19
|
+
from resource_engine.documents import content_disposition
|
|
20
|
+
from resource_engine.errors import ConfigurationError
|
|
21
|
+
from resource_engine.generation import CONTENT_TYPES
|
|
22
|
+
from resource_engine.i18n import get_locale
|
|
23
|
+
from resource_engine.ports.storage import SupportsPresignedUrls
|
|
24
|
+
|
|
25
|
+
_KW = inspect.Parameter.KEYWORD_ONLY
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ExportError(BaseModel):
|
|
29
|
+
"""Why a background export failed."""
|
|
30
|
+
|
|
31
|
+
code: str
|
|
32
|
+
message: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ExportJobOut(BaseModel):
|
|
36
|
+
"""A background export."""
|
|
37
|
+
|
|
38
|
+
id: str = Field(description="Export id")
|
|
39
|
+
resource: str
|
|
40
|
+
format: Literal["csv", "xlsx"]
|
|
41
|
+
status: Literal["pending", "running", "done", "failed"] = Field(
|
|
42
|
+
description="pending, running, done (download it) or failed (see error)"
|
|
43
|
+
)
|
|
44
|
+
rows: int | None = Field(default=None, description="Rows that matched when requested")
|
|
45
|
+
filename: str | None = None
|
|
46
|
+
size: int | None = Field(default=None, description="Size of the file in bytes")
|
|
47
|
+
created_at: str
|
|
48
|
+
started_at: str | None = None
|
|
49
|
+
finished_at: str | None = None
|
|
50
|
+
expires_at: str | None = Field(default=None, description="When the file is deleted")
|
|
51
|
+
error: ExportError | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def build_export_router(
|
|
55
|
+
manager: ResourceManager, *, actor_dependency: Any, redirect_downloads: bool = False
|
|
56
|
+
) -> APIRouter:
|
|
57
|
+
"""The routes that follow background exports and download their files."""
|
|
58
|
+
exports = manager.exports
|
|
59
|
+
assert exports is not None
|
|
60
|
+
router = APIRouter(prefix=f"/{exports.path}", tags=[exports.path])
|
|
61
|
+
|
|
62
|
+
@router.get(
|
|
63
|
+
"/{export_id}",
|
|
64
|
+
response_model=ExportJobOut,
|
|
65
|
+
summary="Status of a background export",
|
|
66
|
+
operation_id="get_export",
|
|
67
|
+
)
|
|
68
|
+
async def get_export(export_id: str = Path(...), actor: Any = Depends(actor_dependency)) -> Any:
|
|
69
|
+
return (await exports.get(export_id, actor=actor)).to_dict()
|
|
70
|
+
|
|
71
|
+
@router.get(
|
|
72
|
+
"/{export_id}/content",
|
|
73
|
+
response_class=StreamingResponse,
|
|
74
|
+
summary="Download a finished export",
|
|
75
|
+
operation_id="download_export",
|
|
76
|
+
responses={
|
|
77
|
+
200: {
|
|
78
|
+
"content": {
|
|
79
|
+
"text/csv": {},
|
|
80
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {},
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
307: {"description": "Redirect to a presigned URL"},
|
|
84
|
+
},
|
|
85
|
+
)
|
|
86
|
+
async def download_export(
|
|
87
|
+
export_id: str = Path(...), actor: Any = Depends(actor_dependency)
|
|
88
|
+
) -> Response:
|
|
89
|
+
if redirect_downloads and isinstance(exports.store, SupportsPresignedUrls):
|
|
90
|
+
url = await exports.download_url(export_id, actor=actor)
|
|
91
|
+
return RedirectResponse(url.url, status_code=307)
|
|
92
|
+
job, stream = await exports.open(export_id, actor=actor)
|
|
93
|
+
from resource_engine.exports import MEDIA_TYPES
|
|
94
|
+
|
|
95
|
+
headers = {
|
|
96
|
+
"Content-Disposition": content_disposition(job.filename or f"{job.id}.{job.format}"),
|
|
97
|
+
"X-Content-Type-Options": "nosniff",
|
|
98
|
+
"Cache-Control": "private, no-store",
|
|
99
|
+
}
|
|
100
|
+
if job.size is not None:
|
|
101
|
+
headers["Content-Length"] = str(job.size)
|
|
102
|
+
return StreamingResponse(stream, media_type=MEDIA_TYPES[job.format], headers=headers)
|
|
103
|
+
|
|
104
|
+
return router
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _printout_endpoint(manager: ResourceManager, resource: str, name: str) -> Any:
|
|
108
|
+
# the manager refuses printouts without a generator (check_printouts)
|
|
109
|
+
generator = manager.generator
|
|
110
|
+
if generator is None:
|
|
111
|
+
raise ConfigurationError(
|
|
112
|
+
f"{resource} has printouts but the manager has no generator",
|
|
113
|
+
hint="Pass ResourceManager(..., generator=DocumentGenerator(...)).",
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
async def endpoint(**kw: Any) -> Response:
|
|
117
|
+
document, filename = await generator.printout(
|
|
118
|
+
manager,
|
|
119
|
+
resource,
|
|
120
|
+
kw["entity_id"],
|
|
121
|
+
name,
|
|
122
|
+
format=kw.get("format"),
|
|
123
|
+
locale=kw.get("locale") or get_locale(), # else the request's language
|
|
124
|
+
actor=kw.get("actor"),
|
|
125
|
+
tenant=kw.get("tenant"),
|
|
126
|
+
)
|
|
127
|
+
return Response(
|
|
128
|
+
document.content,
|
|
129
|
+
media_type=document.content_type,
|
|
130
|
+
headers={
|
|
131
|
+
"Content-Disposition": content_disposition(filename),
|
|
132
|
+
"X-Content-Type-Options": "nosniff",
|
|
133
|
+
"Cache-Control": "private, no-store",
|
|
134
|
+
},
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
return endpoint
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def printout_routes(
|
|
141
|
+
router: APIRouter,
|
|
142
|
+
definition: ResourceDefinition,
|
|
143
|
+
manager: ResourceManager,
|
|
144
|
+
id_param: inspect.Parameter,
|
|
145
|
+
tenant_params: list[inspect.Parameter],
|
|
146
|
+
actor_param: inspect.Parameter,
|
|
147
|
+
) -> None:
|
|
148
|
+
"""``GET /{id}/printouts/<name>`` for each of the resource's printouts."""
|
|
149
|
+
printouts = definition.resource_cls.printouts
|
|
150
|
+
if not printouts or not definition.exposed("get") or manager.generator is None:
|
|
151
|
+
return # without a generator, printouts aren't served
|
|
152
|
+
resource = definition.name
|
|
153
|
+
for printout_name, printout in printouts.items():
|
|
154
|
+
formats = tuple(printout.formats)
|
|
155
|
+
endpoint = _printout_endpoint(manager, resource, printout_name)
|
|
156
|
+
endpoint.__signature__ = inspect.Signature(
|
|
157
|
+
[
|
|
158
|
+
id_param,
|
|
159
|
+
inspect.Parameter(
|
|
160
|
+
"format",
|
|
161
|
+
_KW,
|
|
162
|
+
annotation=Literal[formats],
|
|
163
|
+
default=Query(formats[0], description=f"One of {', '.join(formats)}"),
|
|
164
|
+
),
|
|
165
|
+
inspect.Parameter(
|
|
166
|
+
"locale",
|
|
167
|
+
_KW,
|
|
168
|
+
annotation=str | None,
|
|
169
|
+
default=Query(None, description="Language of the document (ca, es, en...)"),
|
|
170
|
+
),
|
|
171
|
+
*tenant_params,
|
|
172
|
+
actor_param,
|
|
173
|
+
]
|
|
174
|
+
)
|
|
175
|
+
endpoint.__name__ = f"printout_{resource}_{printout_name}"
|
|
176
|
+
router.add_api_route(
|
|
177
|
+
f"/{{entity_id}}/printouts/{printout_name}",
|
|
178
|
+
endpoint,
|
|
179
|
+
methods=["GET"],
|
|
180
|
+
response_class=Response,
|
|
181
|
+
responses={200: {"content": {CONTENT_TYPES[f].split(";")[0]: {} for f in formats}}},
|
|
182
|
+
summary=f"Print {printout_name} for one of {resource}",
|
|
183
|
+
description=printout.description
|
|
184
|
+
or f"The {printout_name} document of the record, rendered now and not stored. "
|
|
185
|
+
"Fields the caller may not read are left out.",
|
|
186
|
+
)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""The language of each request: ``Accept-Language`` negotiated against the
|
|
2
|
+
application's locales, or the signed-in user's ``locale`` claim.
|
|
3
|
+
|
|
4
|
+
```python
|
|
5
|
+
from resource_engine.i18n import Translations, set_translations
|
|
6
|
+
from resource_engine_fastapi import install_locale
|
|
7
|
+
|
|
8
|
+
translations = Translations("invoices/locale", default_locale="ca")
|
|
9
|
+
set_translations(translations)
|
|
10
|
+
install_locale(app, translations)
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Inside the request, ``resource_engine.i18n.gettext`` and error titles
|
|
14
|
+
(``{"error": {"title": ...}}``) use that locale, and the answer carries
|
|
15
|
+
``Content-Language``. JSON data is never translated: front ends translate
|
|
16
|
+
their own texts (``resource-engine i18n export``) and show error titles or
|
|
17
|
+
their own text per ``code``.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from resource_engine.i18n import Translations, get_locale, set_locale, use_locale
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class LocaleMiddleware:
|
|
28
|
+
"""ASGI middleware: picks the request's locale and sets ``Content-Language``."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, app: Any, translations: Translations) -> None:
|
|
31
|
+
self.app = app
|
|
32
|
+
self.translations = translations
|
|
33
|
+
|
|
34
|
+
async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
|
|
35
|
+
"""Handle one ASGI call: pick the locale and set ``Content-Language``."""
|
|
36
|
+
if scope["type"] not in ("http", "websocket"):
|
|
37
|
+
await self.app(scope, receive, send)
|
|
38
|
+
return
|
|
39
|
+
headers = {k.decode().lower(): v.decode() for k, v in scope.get("headers", [])}
|
|
40
|
+
locale = (
|
|
41
|
+
self.translations.negotiate(headers.get("accept-language"))
|
|
42
|
+
or self.translations.default_locale
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
async def send_with_language(message: Any) -> None:
|
|
46
|
+
if message["type"] == "http.response.start":
|
|
47
|
+
current = get_locale()
|
|
48
|
+
if current:
|
|
49
|
+
message.setdefault("headers", [])
|
|
50
|
+
message["headers"] = [
|
|
51
|
+
*message["headers"],
|
|
52
|
+
(b"content-language", current.encode()),
|
|
53
|
+
]
|
|
54
|
+
await send(message)
|
|
55
|
+
|
|
56
|
+
with use_locale(locale):
|
|
57
|
+
await self.app(scope, receive, send_with_language)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def install_locale(app: Any, translations: Translations) -> None:
|
|
61
|
+
"""Negotiate each request's locale (see ``LocaleMiddleware``)."""
|
|
62
|
+
app.add_middleware(LocaleMiddleware, translations=translations)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def principal_locale(principal: Any, translations: Translations) -> None:
|
|
66
|
+
"""Use the signed-in user's ``locale`` claim (OIDC standard claim) when it is
|
|
67
|
+
one of the offered locales: a profile setting beats the browser's."""
|
|
68
|
+
claims = getattr(principal, "claims", None) or {}
|
|
69
|
+
wanted = claims.get("locale")
|
|
70
|
+
if isinstance(wanted, str) and wanted:
|
|
71
|
+
chosen = translations.negotiate(wanted)
|
|
72
|
+
if chosen:
|
|
73
|
+
set_locale(chosen)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
__all__ = ["LocaleMiddleware", "install_locale", "principal_locale"]
|
|
File without changes
|