poli-page-fastapi 0.13.0__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.
- poli_page_fastapi-0.13.0/.gitignore +48 -0
- poli_page_fastapi-0.13.0/CHANGELOG.md +75 -0
- poli_page_fastapi-0.13.0/LICENSE +21 -0
- poli_page_fastapi-0.13.0/PKG-INFO +281 -0
- poli_page_fastapi-0.13.0/README.md +236 -0
- poli_page_fastapi-0.13.0/pyproject.toml +103 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/__init__.py +30 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/_headers.py +40 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/_version.py +1 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/dependencies.py +67 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/exceptions.py +37 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/lifespan.py +27 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/py.typed +0 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/responses.py +192 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/settings.py +90 -0
- poli_page_fastapi-0.13.0/src/poli_page_fastapi/setup.py +47 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# OS
|
|
2
|
+
.DS_Store
|
|
3
|
+
Thumbs.db
|
|
4
|
+
|
|
5
|
+
# Editors
|
|
6
|
+
.vscode/
|
|
7
|
+
.idea/
|
|
8
|
+
*.swp
|
|
9
|
+
|
|
10
|
+
# Node
|
|
11
|
+
node_modules/
|
|
12
|
+
dist/
|
|
13
|
+
build/
|
|
14
|
+
.next/
|
|
15
|
+
*.log
|
|
16
|
+
.npm/
|
|
17
|
+
|
|
18
|
+
# Python
|
|
19
|
+
__pycache__/
|
|
20
|
+
*.py[cod]
|
|
21
|
+
*.egg-info/
|
|
22
|
+
.venv/
|
|
23
|
+
venv/
|
|
24
|
+
.pytest_cache/
|
|
25
|
+
.tox/
|
|
26
|
+
.coverage
|
|
27
|
+
.mypy_cache/
|
|
28
|
+
.ruff_cache/
|
|
29
|
+
|
|
30
|
+
# PHP
|
|
31
|
+
vendor/
|
|
32
|
+
composer.lock
|
|
33
|
+
.phpunit.cache/
|
|
34
|
+
|
|
35
|
+
# Go
|
|
36
|
+
bin/
|
|
37
|
+
*.test
|
|
38
|
+
*.out
|
|
39
|
+
|
|
40
|
+
# Env
|
|
41
|
+
.env
|
|
42
|
+
.env.local
|
|
43
|
+
|
|
44
|
+
# Example-app runtime artifacts
|
|
45
|
+
example-app/output/
|
|
46
|
+
CLAUDE.md
|
|
47
|
+
docs/plan/
|
|
48
|
+
docs/spec/
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.13.0] - 2026-11-04
|
|
11
|
+
|
|
12
|
+
First release on PyPI. It requires the `poli-page` SDK 0.13 (`poli-page>=0.13,<0.14`) and passes the Poli Page API contract v0.13.0. The package shares its major.minor with the Poli Page API, so its first version is 0.13.0; a 0.11.0 was prepared and never published. The Changed, Removed and Fixed entries below describe changes made while it was prepared.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
- `PoliPageSettings(BaseSettings)` — pydantic-settings reader for
|
|
16
|
+
`POLI_PAGE_API_KEY` / `POLI_PAGE_BASE_URL` / `POLI_PAGE_TIMEOUT` /
|
|
17
|
+
`POLI_PAGE_MAX_RETRIES` / `POLI_PAGE_RETRY_DELAY`. Validates the
|
|
18
|
+
`POLI_PAGE_TIMEOUT`, `POLI_PAGE_MAX_RETRIES` and `POLI_PAGE_RETRY_DELAY`
|
|
19
|
+
ranges at construction time; a key that does not match
|
|
20
|
+
`pp_{environment}_{32 hex}` logs one warning.
|
|
21
|
+
- `get_poli_page_client()` — `@lru_cache(maxsize=1)` memoised factory,
|
|
22
|
+
the canonical `Depends(...)` target. Tests inject mocks via
|
|
23
|
+
`app.dependency_overrides[get_poli_page_client]`.
|
|
24
|
+
- `PoliPageDependency` — class-based dependency for per-router clients
|
|
25
|
+
or explicit settings overrides.
|
|
26
|
+
- `PdfResponse`, `PdfStreamResponse`, `PreviewResponse`,
|
|
27
|
+
`DocumentRedirectResponse` — Starlette response subclasses with
|
|
28
|
+
correct `Content-Type`, RFC 5987-encoded `Content-Disposition`,
|
|
29
|
+
`Cache-Control: no-store, private`, and `X-Content-Type-Options:
|
|
30
|
+
nosniff`. PDF responses accept `inline=True` to flip the disposition.
|
|
31
|
+
- `poli_page_exception_handler` — answers a `PoliPageError` with the
|
|
32
|
+
SDK's `to_payload()` body and its status (503 `network_error`, 504
|
|
33
|
+
`timeout`, 502 `invalid_response`, 500 when none, as for
|
|
34
|
+
`invalid_options` and `io_error`); any other exception is re-raised.
|
|
35
|
+
`setup_poli_page` registers it by default;
|
|
36
|
+
`app.add_exception_handler(PoliPageError, poli_page_exception_handler)`
|
|
37
|
+
registers it by hand.
|
|
38
|
+
- `poli_page_lifespan` — async context manager for
|
|
39
|
+
`FastAPI(lifespan=...)` that warms the client at startup and closes
|
|
40
|
+
it (plus clears the factory cache) at shutdown.
|
|
41
|
+
- `example-app/` — runnable FastAPI demo with an interactive dashboard
|
|
42
|
+
at `GET /` exercising every SDK feature.
|
|
43
|
+
- `setup_poli_page(app, *, error_handler=True)`: wraps the app's lifespan in `poli_page_lifespan` (the app's own lifespan and startup/shutdown handlers still run) and registers the error handler, on by default. A `PoliPageError` a route lets through answers `application/json` with the SDK's `to_payload()` body, `{code, message, status, requestId}`, and its `status` (`503` for `network_error`, `504` for `timeout`, `502` for `invalid_response`, `500` when the error has none). `error_handler=False` turns it off.
|
|
44
|
+
- `PdfStreamResponse` accepts the SDK stream as is (`PdfStreamResponse(client.render.pdf_stream(input))`): it enters the stream at once, so a render or download error raises in the route and reaches the error handler, and closes it when the response ends: read to the end, failed, or the client disconnected. Iterators are still accepted.
|
|
45
|
+
- `app = FastAPI()` + `setup_poli_page(app)` sets up both the lifespan and the error handler; `poli_page_lifespan` and `poli_page_exception_handler` stay available to wire by hand. `setup_poli_page` raises `RuntimeError` if the app has already started.
|
|
46
|
+
- Contract tests: `example-app/tests/test_contract.py` runs the API contract's integration cases (`impl.*`) against the example app. CI runs them against the pinned `poli-page/api-contract` v0.13.0, including `impl.invalid-response`, and Dependabot proposes each new contract version.
|
|
47
|
+
- Release workflow (`.github/workflows/release.yml`): a `vX.Y.Z` tag runs the test suite against the pinned API contract, publishes the wheel and sdist to PyPI through Trusted Publishing, and creates the GitHub Release. Before that, the version's major.minor must be the pinned API contract's (a stable contract tag on the pinned commit, not the comment next to it) and the required `poli-page` SDK's (`scripts/check-release-versions.sh`); the error names both versions. See `RELEASING.md`.
|
|
48
|
+
|
|
49
|
+
### Changed (breaking)
|
|
50
|
+
- `PoliPageSettings` accepts environment keys (`pp_{environment}_{32 lowercase hex}`, for example `pp_sandbox_…`, `pp_live_…`, `pp_staging_…`). It no longer raises on a key that is not `pp_test_…` / `pp_live_…`: a missing or empty `POLI_PAGE_API_KEY` still fails when the client is built, any other value is accepted, and a value that does not match the key format logs one warning that shows no part of the key (not even its `pp_{environment}_` prefix) before the API decides. An explicit `PoliPageSettings(api_key=None)` or `api_key=""` leaves the SDK to read `POLI_PAGE_API_KEY`, and that value gets the same check.
|
|
51
|
+
- Requires the `poli-page` SDK 0.13 (`poli-page>=0.13,<0.14`, from PyPI), with environment API keys and no template versions: render inputs carry no `version` and `render.preview` is gone. A missing key raises the SDK's `PoliPageError` with the message `apiKey is required` (code `invalid_options`). With SDK 0.13, a 2xx from the API whose body is not JSON (usually from a proxy) raises `InvalidResponseError`, code `invalid_response` (it was a raw `json.JSONDecodeError`), which the error handler answers `502`; a `render_to_file()` that cannot write its file raises `io_error` (it was the `OSError` itself), answered `500` with `"status": null`; and the PDF download is bounded by the `timeout` setting (an idle timeout for `render.pdf_stream`), a download that outlasts it raising `DOWNLOAD_FAILED`.
|
|
52
|
+
- `poli_page_exception_handler` answers with the SDK's `to_payload()` body as is: an error with no status answers `500` with `"status": null` in the body (it used to copy `500` into the body). Any exception that is not a `PoliPageError` is re-raised instead of being answered as a hand-built `{"code": "UNKNOWN", …}`.
|
|
53
|
+
- `PreviewResponse` is documented for `client.documents.preview` (the stored HTML of a rendered document).
|
|
54
|
+
- Example app: no `version` in any render; `GET /errors/not-found` (template `does-not-exist`, `404 TEMPLATE_NOT_FOUND`) replaces `GET /errors/bad-version`. The app is set up with `setup_poli_page(app)`, so that route answers through the default error handler. `GET /render/stream` passes the SDK stream to `PdfStreamResponse`, so a render error answers the handler's JSON instead of a `200` PDF with an empty body. The app loads `example-app/.env` instead of a `.env` above the repository.
|
|
55
|
+
- The integration test runs only with a sandbox key (`pp_sandbox_…`).
|
|
56
|
+
|
|
57
|
+
### CI
|
|
58
|
+
- The live API job runs on `main` (and on demand) against the production API with the sandbox key from the `POLI_PAGE_API_KEY` secret, and skips with a notice when the key is absent or not a `pp_sandbox_` key. It passes the optional `POLI_PAGE_BASE_URL` secret to the integration test (unset: the SDK default).
|
|
59
|
+
|
|
60
|
+
### Removed
|
|
61
|
+
- Example app: `GET /render/preview` and its dashboard button (`render.preview` no longer exists in the SDK).
|
|
62
|
+
|
|
63
|
+
### Fixed
|
|
64
|
+
- `PdfStreamResponse` closes the SDK stream before it runs its `background` task. After a
|
|
65
|
+
client disconnect, the stream's connection used to stay open until the task finished.
|
|
66
|
+
- `PdfResponse` / `PdfStreamResponse`: the `Content-Disposition` filename is now escaped per RFC 6266 / RFC 9110 (`\` and `"` as quoted-pairs, ASCII fallback included) and stripped of control characters (CR/LF, TAB, DEL, C1), so a filename can no longer break the header or inject parameters.
|
|
67
|
+
|
|
68
|
+
### Compatibility
|
|
69
|
+
- Python 3.11, 3.12, 3.13
|
|
70
|
+
- FastAPI `^0.100`, `^0.110`
|
|
71
|
+
- Pydantic v2 + pydantic-settings v2
|
|
72
|
+
- `poli-page>=0.13,<0.14`
|
|
73
|
+
|
|
74
|
+
[Unreleased]: https://github.com/poli-page/fastapi/compare/v0.13.0...HEAD
|
|
75
|
+
[0.13.0]: https://github.com/poli-page/fastapi/releases/tag/v0.13.0
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Poli Page
|
|
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,281 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: poli-page-fastapi
|
|
3
|
+
Version: 0.13.0
|
|
4
|
+
Summary: FastAPI integration for the Poli Page PDF rendering API
|
|
5
|
+
Project-URL: Homepage, https://poli.page
|
|
6
|
+
Project-URL: Documentation, https://docs.poli.page/reference/sdk/
|
|
7
|
+
Project-URL: Source, https://github.com/poli-page/fastapi
|
|
8
|
+
Project-URL: Issues, https://github.com/poli-page/fastapi/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/poli-page/fastapi/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Release-Notes, https://github.com/poli-page/fastapi/releases
|
|
11
|
+
Author: Poli Page
|
|
12
|
+
License: MIT
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Keywords: fastapi,html,pdf,poli-page,rendering,starlette,template
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Environment :: Web Environment
|
|
17
|
+
Classifier: Framework :: AsyncIO
|
|
18
|
+
Classifier: Framework :: FastAPI
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
21
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.11
|
|
28
|
+
Requires-Dist: anyio>=3.7
|
|
29
|
+
Requires-Dist: fastapi<1.0,>=0.100
|
|
30
|
+
Requires-Dist: poli-page<0.14,>=0.13
|
|
31
|
+
Requires-Dist: pydantic-settings<3,>=2.0
|
|
32
|
+
Requires-Dist: pydantic<3,>=2.0
|
|
33
|
+
Provides-Extra: dev
|
|
34
|
+
Requires-Dist: build>=1; extra == 'dev'
|
|
35
|
+
Requires-Dist: httpx>=0.25; extra == 'dev'
|
|
36
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
37
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
38
|
+
Requires-Dist: pytest-mock>=3.12; extra == 'dev'
|
|
39
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
40
|
+
Requires-Dist: python-dotenv>=1.0; extra == 'dev'
|
|
41
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
42
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
43
|
+
Requires-Dist: twine>=7; extra == 'dev'
|
|
44
|
+
Description-Content-Type: text/markdown
|
|
45
|
+
|
|
46
|
+
# poli-page-fastapi
|
|
47
|
+
|
|
48
|
+
> Render Poli Page documents from FastAPI endpoints.
|
|
49
|
+
|
|
50
|
+
## About
|
|
51
|
+
|
|
52
|
+
This package exposes the Poli Page Python SDK as a FastAPI dependency: a memoised client factory you inject with `Depends()`, Starlette response subclasses that ship the correct PDF headers, and a pydantic-settings reader for `POLI_PAGE_*` env vars. It is a thin wrapper around [`poli-page`](https://pypi.org/project/poli-page/) — the SDK owns transport, retries, error classification, and stream chunking.
|
|
53
|
+
|
|
54
|
+
**When to use this:**
|
|
55
|
+
|
|
56
|
+
- You return generated PDFs from FastAPI routes and want `Depends()` instead of a hand-rolled global client.
|
|
57
|
+
- You want correct `Content-Type`, RFC 5987 `Content-Disposition`, and `Cache-Control` headers without writing them yourself.
|
|
58
|
+
- You want exceptions raised by the SDK to surface as typed JSON responses.
|
|
59
|
+
|
|
60
|
+
**When not to:**
|
|
61
|
+
|
|
62
|
+
- You are not on FastAPI — use [`poli-page`](https://pypi.org/project/poli-page/) directly, or the integration for your framework.
|
|
63
|
+
- You need a CLI command, an `APIRoute` subclass, or an automatic OpenAPI extension — this package ships none of those by design.
|
|
64
|
+
|
|
65
|
+
## Requirements
|
|
66
|
+
|
|
67
|
+
- Python 3.11, 3.12, or 3.13
|
|
68
|
+
- FastAPI `>=0.100,<1.0`
|
|
69
|
+
- Pydantic v2 and pydantic-settings v2
|
|
70
|
+
- The `poli-page` Python SDK 0.13.x (installed with the package, `poli-page>=0.13,<0.14`)
|
|
71
|
+
|
|
72
|
+
## Install
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install poli-page-fastapi
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
This installs the `poli-page` SDK 0.13.x with it.
|
|
79
|
+
|
|
80
|
+
Set the API key in your environment before the app starts:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
# .env (or your shell)
|
|
84
|
+
POLI_PAGE_API_KEY=pp_sandbox_...
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Get a key at [app.poli.page/settings/api-keys](https://app.poli.page/settings/api-keys). The package does not call `load_dotenv()` for you — load the file yourself, or rely on pydantic-settings' `SettingsConfigDict(env_file=...)`.
|
|
88
|
+
|
|
89
|
+
## API keys
|
|
90
|
+
|
|
91
|
+
A key is `pp_{environment}_{32 lowercase hex}` and belongs to one environment of your organization. The key alone selects the environment, and so which published copy of a project renders: render inputs carry no version.
|
|
92
|
+
|
|
93
|
+
| Environment | Key | Watermark | Counted |
|
|
94
|
+
| ------------------------------------- | -------------- | --------- | ------- |
|
|
95
|
+
| `sandbox` (every org) | `pp_sandbox_…` | yes | no |
|
|
96
|
+
| `live` (every org, deletable on Pro+) | `pp_live_…` | no | yes |
|
|
97
|
+
| created on Pro+ (e.g. `staging`) | `pp_staging_…` | no | yes |
|
|
98
|
+
|
|
99
|
+
"Counted" means the render counts toward the organization's monthly PDF quota.
|
|
100
|
+
|
|
101
|
+
The API is the only authority on keys. This package checks only that `POLI_PAGE_API_KEY` is set and not empty. A value that does not match `pp_{environment}_{32 lowercase hex}` logs one warning through the `poli_page_fastapi.settings` logger, which names the expected format and shows no part of the key, and the client starts anyway: the API answers `401 INVALID_API_KEY` (or `401 MISSING_API_KEY` for a value without `pp_`) if the key is not valid. A key passed explicitly (`PoliPageSettings(api_key=…)`) gets the same check. When that explicit value is `None` or empty, the client is built without a key and the SDK reads `POLI_PAGE_API_KEY` itself, so that value is checked instead.
|
|
102
|
+
|
|
103
|
+
## Quick start
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
# main.py
|
|
107
|
+
from typing import Annotated
|
|
108
|
+
|
|
109
|
+
from fastapi import Depends, FastAPI
|
|
110
|
+
from poli_page import PoliPage
|
|
111
|
+
from poli_page_fastapi import PdfResponse, get_poli_page_client, setup_poli_page
|
|
112
|
+
|
|
113
|
+
app = FastAPI()
|
|
114
|
+
setup_poli_page(app) # client lifespan + error handler
|
|
115
|
+
|
|
116
|
+
Client = Annotated[PoliPage, Depends(get_poli_page_client)]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@app.get("/invoice/{invoice_id}.pdf", response_class=PdfResponse)
|
|
120
|
+
def invoice_pdf(invoice_id: str, client: Client) -> PdfResponse:
|
|
121
|
+
pdf = client.render.pdf({
|
|
122
|
+
"project": "invoices",
|
|
123
|
+
"template": "monthly",
|
|
124
|
+
"data": {"invoice_id": invoice_id},
|
|
125
|
+
})
|
|
126
|
+
return PdfResponse(pdf, filename=f"invoice-{invoice_id}.pdf")
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Run with `uvicorn main:app` and `GET /invoice/42.pdf` returns a PDF with the correct headers. `setup_poli_page(app)` builds the client at startup, closes it at shutdown (your own `lifespan` still runs, inside it), and registers the error handler (see [Errors](#errors)).
|
|
130
|
+
|
|
131
|
+
## Configuration
|
|
132
|
+
|
|
133
|
+
`PoliPageSettings` reads `POLI_PAGE_*` env vars and maps one-to-one with the SDK's `PoliPage(__init__)` kwargs. Unset fields fall through to the SDK's defaults.
|
|
134
|
+
|
|
135
|
+
| Env var | Field | Type | Notes |
|
|
136
|
+
| ------------------------ | ------------- | ------- | ------------------------------------------- |
|
|
137
|
+
| `POLI_PAGE_API_KEY` | `api_key` | `str` | Required: missing or empty, building the client raises `PoliPageError`. A value that is not `pp_{environment}_{32 lowercase hex}` logs one warning, then the API decides (see [API keys](#api-keys)). |
|
|
138
|
+
| `POLI_PAGE_BASE_URL` | `base_url` | `str` | Override for sandbox or regional endpoints. |
|
|
139
|
+
| `POLI_PAGE_TIMEOUT` | `timeout` | `float` | Per-request timeout in seconds, `(0, 600]`. It also bounds the PDF download: a download that outlasts it raises `DOWNLOAD_FAILED` (answered `500`), not `timeout`. |
|
|
140
|
+
| `POLI_PAGE_MAX_RETRIES` | `max_retries` | `int` | Retries per failed request, `[0, 10]`. |
|
|
141
|
+
| `POLI_PAGE_RETRY_DELAY` | `retry_delay` | `float` | Initial backoff in seconds, `[0, 30]`. |
|
|
142
|
+
|
|
143
|
+
To use explicit settings on a per-router or per-endpoint basis, pass a `PoliPageSettings` instance to `PoliPageDependency`:
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
# main.py
|
|
147
|
+
import os
|
|
148
|
+
|
|
149
|
+
from poli_page_fastapi import PoliPageDependency, PoliPageSettings
|
|
150
|
+
|
|
151
|
+
sandbox = PoliPageDependency(
|
|
152
|
+
settings=PoliPageSettings(api_key=os.environ["POLI_PAGE_API_KEY"]),
|
|
153
|
+
)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## API at a glance
|
|
157
|
+
|
|
158
|
+
| Symbol | Purpose |
|
|
159
|
+
| --------------------------- | ---------------------------------------------------------------------- |
|
|
160
|
+
| `get_poli_page_client` | `@lru_cache` memoised factory — the canonical `Depends(...)` target. |
|
|
161
|
+
| `PoliPageDependency` | Class-based dependency for per-router or per-instance settings. |
|
|
162
|
+
| `PoliPageSettings` | Pydantic-settings reader for `POLI_PAGE_*` env vars. |
|
|
163
|
+
| `PdfResponse` | `Response` subclass for `client.render.pdf` bytes. |
|
|
164
|
+
| `PdfStreamResponse` | `StreamingResponse` subclass for `client.render.pdf_stream(...)`: pass the SDK stream as is, so SDK errors reach the error handler. |
|
|
165
|
+
| `PreviewResponse` | `text/html` response for the stored HTML from `client.documents.preview`. |
|
|
166
|
+
| `DocumentRedirectResponse` | 302/308 redirect to a presigned document URL. |
|
|
167
|
+
| `setup_poli_page` | Sets up an app: the client lifespan and the error handler (on by default). |
|
|
168
|
+
| `poli_page_exception_handler` | The error handler: answers a `PoliPageError` with its `to_payload()` JSON. |
|
|
169
|
+
| `poli_page_lifespan` | ASGI lifespan that warms the client on startup and closes on shutdown. |
|
|
170
|
+
|
|
171
|
+
Full reference: the exports of [`src/poli_page_fastapi/__init__.py`](https://github.com/poli-page/fastapi/blob/main/src/poli_page_fastapi/__init__.py) and their docstrings, and the [SDK reference](https://docs.poli.page/reference/sdk/).
|
|
172
|
+
|
|
173
|
+
## Errors
|
|
174
|
+
|
|
175
|
+
### Error handler (on by default)
|
|
176
|
+
|
|
177
|
+
`setup_poli_page(app)` registers `poli_page_exception_handler` for `PoliPageError`. A route that lets an SDK error through answers JSON:
|
|
178
|
+
|
|
179
|
+
- the body is the SDK's `exc.to_payload()`, exactly `{"code", "message", "status", "requestId"}`;
|
|
180
|
+
- the HTTP status is that payload's `status`: the API's status for an API error, `503` for `network_error`, `504` for `timeout`, `502` for `invalid_response` (a `2xx` whose body is not JSON, usually from a proxy between the SDK and the API), and `500` when the error has none, such as `io_error` (`render_to_file` could not write the file) or a `DOWNLOAD_FAILED` without a storage status (the body's `status` is then `null`);
|
|
181
|
+
- `Content-Type: application/json`, with `Cache-Control: no-store, private`.
|
|
182
|
+
|
|
183
|
+
```json
|
|
184
|
+
{
|
|
185
|
+
"code": "TEMPLATE_NOT_FOUND",
|
|
186
|
+
"message": "Template 'does-not-exist' not found in project 'getting-started'.",
|
|
187
|
+
"status": 404,
|
|
188
|
+
"requestId": "req_..."
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Other exceptions are not touched. To handle SDK errors yourself, turn the handler off:
|
|
193
|
+
|
|
194
|
+
```python
|
|
195
|
+
setup_poli_page(app, error_handler=False)
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`FastAPI(lifespan=poli_page_lifespan)` on its own registers no handler: use `setup_poli_page(app)` instead (not both, or the client lifespan runs twice), or register the handler yourself with `app.add_exception_handler(PoliPageError, poli_page_exception_handler)`. Call `setup_poli_page` before the app starts; afterwards it raises `RuntimeError`.
|
|
199
|
+
|
|
200
|
+
For a streamed PDF, pass the SDK stream to `PdfStreamResponse` as is, `PdfStreamResponse(client.render.pdf_stream(input))`, instead of opening it inside a generator: an error raised once the body is streaming comes after the `200` is sent, and no handler can answer it. The response closes the stream when it ends, including when the client disconnects, and before it runs a `background` task. Opening the stream sends the render and the download's first request synchronously, so build the response in a `def` route (FastAPI runs it in its threadpool), or through `run_in_threadpool` in an `async def` route.
|
|
201
|
+
|
|
202
|
+
### Error types
|
|
203
|
+
|
|
204
|
+
The SDK raises one exception family rooted at `PoliPageError`. The four categories in the shared taxonomy map to these SDK classes:
|
|
205
|
+
|
|
206
|
+
- **Auth** — `AuthenticationError`
|
|
207
|
+
- **Rate limit** — `RateLimitError`
|
|
208
|
+
- **Request rejected** — `BadRequestError`, `UnprocessableEntityError` (4xx subclasses of `APIStatusError`)
|
|
209
|
+
- **Network / transport** — `APIConnectionError`, `APITimeoutError`
|
|
210
|
+
|
|
211
|
+
Two more codes come from the SDK itself: `invalid_response` (`InvalidResponseError`, a `2xx` whose body is not JSON) and `io_error` (a `PoliPageError` from `render_to_file` when it cannot write the file, with the `OSError` as `__cause__`).
|
|
212
|
+
|
|
213
|
+
Catch one in the route when it needs its own answer:
|
|
214
|
+
|
|
215
|
+
```python
|
|
216
|
+
# main.py
|
|
217
|
+
from fastapi.responses import JSONResponse
|
|
218
|
+
from poli_page import RateLimitError
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@app.get("/invoice/{invoice_id}.pdf")
|
|
222
|
+
def invoice_pdf(invoice_id: str, client: Client) -> PdfResponse:
|
|
223
|
+
try:
|
|
224
|
+
pdf = client.render.pdf({"project": "...", "template": "...", "data": {}})
|
|
225
|
+
except RateLimitError as exc:
|
|
226
|
+
return JSONResponse(
|
|
227
|
+
status_code=429,
|
|
228
|
+
content={"retry_after": exc.response.headers.get("Retry-After")},
|
|
229
|
+
)
|
|
230
|
+
return PdfResponse(pdf, filename=f"invoice-{invoice_id}.pdf")
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
## Example app
|
|
234
|
+
|
|
235
|
+
[`example-app/`](https://github.com/poli-page/fastapi/tree/main/example-app) is a self-contained FastAPI app with an interactive dashboard at `GET /`. It exercises every SDK method — `render.pdf`, `render.pdf_stream`, `render.document`, document retrieval, `documents.preview`, thumbnails, and deletion — and demonstrates `setup_poli_page()`, `Depends()`, the response helpers and the default error handler (`GET /errors/not-found` answers `404 TEMPLATE_NOT_FOUND`). Set `POLI_PAGE_API_KEY` to a sandbox key (`pp_sandbox_…`); `POLI_PAGE_BASE_URL` is optional.
|
|
236
|
+
|
|
237
|
+
```bash
|
|
238
|
+
cd example-app
|
|
239
|
+
uv sync
|
|
240
|
+
uv run uvicorn main:app --reload --port 8000
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Open <http://localhost:8000>.
|
|
244
|
+
|
|
245
|
+
## Going further
|
|
246
|
+
|
|
247
|
+
The following deep dives are forthcoming under `docs/`:
|
|
248
|
+
|
|
249
|
+
- `docs/lifespan.md` — wiring `poli_page_lifespan` by hand instead of `setup_poli_page`.
|
|
250
|
+
- `docs/async.md` — calling the sync client from `async def` routes via `run_in_threadpool`, and the path to the native `AsyncPoliPage`.
|
|
251
|
+
- `docs/testing.md` — overriding `get_poli_page_client` with `app.dependency_overrides`, and the `TestClient` context-manager requirement.
|
|
252
|
+
- `docs/errors.md` — the full status mapping the global exception handler applies.
|
|
253
|
+
- `docs/responses.md` — RFC 5987 filename encoding, `inline=True`, and streaming responses.
|
|
254
|
+
|
|
255
|
+
## Compatibility
|
|
256
|
+
|
|
257
|
+
| Package version | `poli-page` SDK | FastAPI | Python |
|
|
258
|
+
| --------------- | --------------- | ---------------------- | ------------------- |
|
|
259
|
+
| 0.13.x | 0.13.x | `^0.100`, `^0.110` | 3.11, 3.12, 3.13 |
|
|
260
|
+
|
|
261
|
+
Tested against the FastAPI versions listed above; other 0.x releases in that range are expected to work. The package shares its major.minor with the Poli Page API and requires the SDK of the same minor: `poli-page>=0.13,<0.14`.
|
|
262
|
+
|
|
263
|
+
## Contributing
|
|
264
|
+
|
|
265
|
+
Run the checks CI runs from the repository root: `uv sync --all-extras`, then `uv run ruff check .`, `uv run ruff format --check .`, `uv run mypy src tests example-app/tests` and `uv run pytest tests/unit`.
|
|
266
|
+
|
|
267
|
+
### Contract tests
|
|
268
|
+
|
|
269
|
+
`example-app/tests/test_contract.py` runs the integration cases (`kind: "impl"`) of the [Poli Page API contract](https://github.com/poli-page/api-contract) against the example app: a local server plays the API, the app's SDK points at it through `POLI_PAGE_BASE_URL`, and FastAPI's `TestClient` checks each answer. CI runs them against the contract version pinned in `.github/workflows/ci.yml`. Locally:
|
|
270
|
+
|
|
271
|
+
```bash
|
|
272
|
+
cd example-app
|
|
273
|
+
uv sync
|
|
274
|
+
POLI_CONTRACT=<path to contract.json> uv run pytest
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
Without `POLI_CONTRACT` the test is skipped (in CI it fails). `example-app/tests/contract-skip.json` lists the cases allowed to fail, each with its reason.
|
|
278
|
+
|
|
279
|
+
## License
|
|
280
|
+
|
|
281
|
+
Released under the MIT License — see [LICENSE](https://github.com/poli-page/fastapi/blob/main/LICENSE).
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
# poli-page-fastapi
|
|
2
|
+
|
|
3
|
+
> Render Poli Page documents from FastAPI endpoints.
|
|
4
|
+
|
|
5
|
+
## About
|
|
6
|
+
|
|
7
|
+
This package exposes the Poli Page Python SDK as a FastAPI dependency: a memoised client factory you inject with `Depends()`, Starlette response subclasses that ship the correct PDF headers, and a pydantic-settings reader for `POLI_PAGE_*` env vars. It is a thin wrapper around [`poli-page`](https://pypi.org/project/poli-page/) — the SDK owns transport, retries, error classification, and stream chunking.
|
|
8
|
+
|
|
9
|
+
**When to use this:**
|
|
10
|
+
|
|
11
|
+
- You return generated PDFs from FastAPI routes and want `Depends()` instead of a hand-rolled global client.
|
|
12
|
+
- You want correct `Content-Type`, RFC 5987 `Content-Disposition`, and `Cache-Control` headers without writing them yourself.
|
|
13
|
+
- You want exceptions raised by the SDK to surface as typed JSON responses.
|
|
14
|
+
|
|
15
|
+
**When not to:**
|
|
16
|
+
|
|
17
|
+
- You are not on FastAPI — use [`poli-page`](https://pypi.org/project/poli-page/) directly, or the integration for your framework.
|
|
18
|
+
- You need a CLI command, an `APIRoute` subclass, or an automatic OpenAPI extension — this package ships none of those by design.
|
|
19
|
+
|
|
20
|
+
## Requirements
|
|
21
|
+
|
|
22
|
+
- Python 3.11, 3.12, or 3.13
|
|
23
|
+
- FastAPI `>=0.100,<1.0`
|
|
24
|
+
- Pydantic v2 and pydantic-settings v2
|
|
25
|
+
- The `poli-page` Python SDK 0.13.x (installed with the package, `poli-page>=0.13,<0.14`)
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install poli-page-fastapi
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
This installs the `poli-page` SDK 0.13.x with it.
|
|
34
|
+
|
|
35
|
+
Set the API key in your environment before the app starts:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
# .env (or your shell)
|
|
39
|
+
POLI_PAGE_API_KEY=pp_sandbox_...
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Get a key at [app.poli.page/settings/api-keys](https://app.poli.page/settings/api-keys). The package does not call `load_dotenv()` for you — load the file yourself, or rely on pydantic-settings' `SettingsConfigDict(env_file=...)`.
|
|
43
|
+
|
|
44
|
+
## API keys
|
|
45
|
+
|
|
46
|
+
A key is `pp_{environment}_{32 lowercase hex}` and belongs to one environment of your organization. The key alone selects the environment, and so which published copy of a project renders: render inputs carry no version.
|
|
47
|
+
|
|
48
|
+
| Environment | Key | Watermark | Counted |
|
|
49
|
+
| ------------------------------------- | -------------- | --------- | ------- |
|
|
50
|
+
| `sandbox` (every org) | `pp_sandbox_…` | yes | no |
|
|
51
|
+
| `live` (every org, deletable on Pro+) | `pp_live_…` | no | yes |
|
|
52
|
+
| created on Pro+ (e.g. `staging`) | `pp_staging_…` | no | yes |
|
|
53
|
+
|
|
54
|
+
"Counted" means the render counts toward the organization's monthly PDF quota.
|
|
55
|
+
|
|
56
|
+
The API is the only authority on keys. This package checks only that `POLI_PAGE_API_KEY` is set and not empty. A value that does not match `pp_{environment}_{32 lowercase hex}` logs one warning through the `poli_page_fastapi.settings` logger, which names the expected format and shows no part of the key, and the client starts anyway: the API answers `401 INVALID_API_KEY` (or `401 MISSING_API_KEY` for a value without `pp_`) if the key is not valid. A key passed explicitly (`PoliPageSettings(api_key=…)`) gets the same check. When that explicit value is `None` or empty, the client is built without a key and the SDK reads `POLI_PAGE_API_KEY` itself, so that value is checked instead.
|
|
57
|
+
|
|
58
|
+
## Quick start
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
# main.py
|
|
62
|
+
from typing import Annotated
|
|
63
|
+
|
|
64
|
+
from fastapi import Depends, FastAPI
|
|
65
|
+
from poli_page import PoliPage
|
|
66
|
+
from poli_page_fastapi import PdfResponse, get_poli_page_client, setup_poli_page
|
|
67
|
+
|
|
68
|
+
app = FastAPI()
|
|
69
|
+
setup_poli_page(app) # client lifespan + error handler
|
|
70
|
+
|
|
71
|
+
Client = Annotated[PoliPage, Depends(get_poli_page_client)]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@app.get("/invoice/{invoice_id}.pdf", response_class=PdfResponse)
|
|
75
|
+
def invoice_pdf(invoice_id: str, client: Client) -> PdfResponse:
|
|
76
|
+
pdf = client.render.pdf({
|
|
77
|
+
"project": "invoices",
|
|
78
|
+
"template": "monthly",
|
|
79
|
+
"data": {"invoice_id": invoice_id},
|
|
80
|
+
})
|
|
81
|
+
return PdfResponse(pdf, filename=f"invoice-{invoice_id}.pdf")
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Run with `uvicorn main:app` and `GET /invoice/42.pdf` returns a PDF with the correct headers. `setup_poli_page(app)` builds the client at startup, closes it at shutdown (your own `lifespan` still runs, inside it), and registers the error handler (see [Errors](#errors)).
|
|
85
|
+
|
|
86
|
+
## Configuration
|
|
87
|
+
|
|
88
|
+
`PoliPageSettings` reads `POLI_PAGE_*` env vars and maps one-to-one with the SDK's `PoliPage(__init__)` kwargs. Unset fields fall through to the SDK's defaults.
|
|
89
|
+
|
|
90
|
+
| Env var | Field | Type | Notes |
|
|
91
|
+
| ------------------------ | ------------- | ------- | ------------------------------------------- |
|
|
92
|
+
| `POLI_PAGE_API_KEY` | `api_key` | `str` | Required: missing or empty, building the client raises `PoliPageError`. A value that is not `pp_{environment}_{32 lowercase hex}` logs one warning, then the API decides (see [API keys](#api-keys)). |
|
|
93
|
+
| `POLI_PAGE_BASE_URL` | `base_url` | `str` | Override for sandbox or regional endpoints. |
|
|
94
|
+
| `POLI_PAGE_TIMEOUT` | `timeout` | `float` | Per-request timeout in seconds, `(0, 600]`. It also bounds the PDF download: a download that outlasts it raises `DOWNLOAD_FAILED` (answered `500`), not `timeout`. |
|
|
95
|
+
| `POLI_PAGE_MAX_RETRIES` | `max_retries` | `int` | Retries per failed request, `[0, 10]`. |
|
|
96
|
+
| `POLI_PAGE_RETRY_DELAY` | `retry_delay` | `float` | Initial backoff in seconds, `[0, 30]`. |
|
|
97
|
+
|
|
98
|
+
To use explicit settings on a per-router or per-endpoint basis, pass a `PoliPageSettings` instance to `PoliPageDependency`:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
# main.py
|
|
102
|
+
import os
|
|
103
|
+
|
|
104
|
+
from poli_page_fastapi import PoliPageDependency, PoliPageSettings
|
|
105
|
+
|
|
106
|
+
sandbox = PoliPageDependency(
|
|
107
|
+
settings=PoliPageSettings(api_key=os.environ["POLI_PAGE_API_KEY"]),
|
|
108
|
+
)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## API at a glance
|
|
112
|
+
|
|
113
|
+
| Symbol | Purpose |
|
|
114
|
+
| --------------------------- | ---------------------------------------------------------------------- |
|
|
115
|
+
| `get_poli_page_client` | `@lru_cache` memoised factory — the canonical `Depends(...)` target. |
|
|
116
|
+
| `PoliPageDependency` | Class-based dependency for per-router or per-instance settings. |
|
|
117
|
+
| `PoliPageSettings` | Pydantic-settings reader for `POLI_PAGE_*` env vars. |
|
|
118
|
+
| `PdfResponse` | `Response` subclass for `client.render.pdf` bytes. |
|
|
119
|
+
| `PdfStreamResponse` | `StreamingResponse` subclass for `client.render.pdf_stream(...)`: pass the SDK stream as is, so SDK errors reach the error handler. |
|
|
120
|
+
| `PreviewResponse` | `text/html` response for the stored HTML from `client.documents.preview`. |
|
|
121
|
+
| `DocumentRedirectResponse` | 302/308 redirect to a presigned document URL. |
|
|
122
|
+
| `setup_poli_page` | Sets up an app: the client lifespan and the error handler (on by default). |
|
|
123
|
+
| `poli_page_exception_handler` | The error handler: answers a `PoliPageError` with its `to_payload()` JSON. |
|
|
124
|
+
| `poli_page_lifespan` | ASGI lifespan that warms the client on startup and closes on shutdown. |
|
|
125
|
+
|
|
126
|
+
Full reference: the exports of [`src/poli_page_fastapi/__init__.py`](https://github.com/poli-page/fastapi/blob/main/src/poli_page_fastapi/__init__.py) and their docstrings, and the [SDK reference](https://docs.poli.page/reference/sdk/).
|
|
127
|
+
|
|
128
|
+
## Errors
|
|
129
|
+
|
|
130
|
+
### Error handler (on by default)
|
|
131
|
+
|
|
132
|
+
`setup_poli_page(app)` registers `poli_page_exception_handler` for `PoliPageError`. A route that lets an SDK error through answers JSON:
|
|
133
|
+
|
|
134
|
+
- the body is the SDK's `exc.to_payload()`, exactly `{"code", "message", "status", "requestId"}`;
|
|
135
|
+
- the HTTP status is that payload's `status`: the API's status for an API error, `503` for `network_error`, `504` for `timeout`, `502` for `invalid_response` (a `2xx` whose body is not JSON, usually from a proxy between the SDK and the API), and `500` when the error has none, such as `io_error` (`render_to_file` could not write the file) or a `DOWNLOAD_FAILED` without a storage status (the body's `status` is then `null`);
|
|
136
|
+
- `Content-Type: application/json`, with `Cache-Control: no-store, private`.
|
|
137
|
+
|
|
138
|
+
```json
|
|
139
|
+
{
|
|
140
|
+
"code": "TEMPLATE_NOT_FOUND",
|
|
141
|
+
"message": "Template 'does-not-exist' not found in project 'getting-started'.",
|
|
142
|
+
"status": 404,
|
|
143
|
+
"requestId": "req_..."
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Other exceptions are not touched. To handle SDK errors yourself, turn the handler off:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
setup_poli_page(app, error_handler=False)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`FastAPI(lifespan=poli_page_lifespan)` on its own registers no handler: use `setup_poli_page(app)` instead (not both, or the client lifespan runs twice), or register the handler yourself with `app.add_exception_handler(PoliPageError, poli_page_exception_handler)`. Call `setup_poli_page` before the app starts; afterwards it raises `RuntimeError`.
|
|
154
|
+
|
|
155
|
+
For a streamed PDF, pass the SDK stream to `PdfStreamResponse` as is, `PdfStreamResponse(client.render.pdf_stream(input))`, instead of opening it inside a generator: an error raised once the body is streaming comes after the `200` is sent, and no handler can answer it. The response closes the stream when it ends, including when the client disconnects, and before it runs a `background` task. Opening the stream sends the render and the download's first request synchronously, so build the response in a `def` route (FastAPI runs it in its threadpool), or through `run_in_threadpool` in an `async def` route.
|
|
156
|
+
|
|
157
|
+
### Error types
|
|
158
|
+
|
|
159
|
+
The SDK raises one exception family rooted at `PoliPageError`. The four categories in the shared taxonomy map to these SDK classes:
|
|
160
|
+
|
|
161
|
+
- **Auth** — `AuthenticationError`
|
|
162
|
+
- **Rate limit** — `RateLimitError`
|
|
163
|
+
- **Request rejected** — `BadRequestError`, `UnprocessableEntityError` (4xx subclasses of `APIStatusError`)
|
|
164
|
+
- **Network / transport** — `APIConnectionError`, `APITimeoutError`
|
|
165
|
+
|
|
166
|
+
Two more codes come from the SDK itself: `invalid_response` (`InvalidResponseError`, a `2xx` whose body is not JSON) and `io_error` (a `PoliPageError` from `render_to_file` when it cannot write the file, with the `OSError` as `__cause__`).
|
|
167
|
+
|
|
168
|
+
Catch one in the route when it needs its own answer:
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
# main.py
|
|
172
|
+
from fastapi.responses import JSONResponse
|
|
173
|
+
from poli_page import RateLimitError
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@app.get("/invoice/{invoice_id}.pdf")
|
|
177
|
+
def invoice_pdf(invoice_id: str, client: Client) -> PdfResponse:
|
|
178
|
+
try:
|
|
179
|
+
pdf = client.render.pdf({"project": "...", "template": "...", "data": {}})
|
|
180
|
+
except RateLimitError as exc:
|
|
181
|
+
return JSONResponse(
|
|
182
|
+
status_code=429,
|
|
183
|
+
content={"retry_after": exc.response.headers.get("Retry-After")},
|
|
184
|
+
)
|
|
185
|
+
return PdfResponse(pdf, filename=f"invoice-{invoice_id}.pdf")
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
## Example app
|
|
189
|
+
|
|
190
|
+
[`example-app/`](https://github.com/poli-page/fastapi/tree/main/example-app) is a self-contained FastAPI app with an interactive dashboard at `GET /`. It exercises every SDK method — `render.pdf`, `render.pdf_stream`, `render.document`, document retrieval, `documents.preview`, thumbnails, and deletion — and demonstrates `setup_poli_page()`, `Depends()`, the response helpers and the default error handler (`GET /errors/not-found` answers `404 TEMPLATE_NOT_FOUND`). Set `POLI_PAGE_API_KEY` to a sandbox key (`pp_sandbox_…`); `POLI_PAGE_BASE_URL` is optional.
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
cd example-app
|
|
194
|
+
uv sync
|
|
195
|
+
uv run uvicorn main:app --reload --port 8000
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Open <http://localhost:8000>.
|
|
199
|
+
|
|
200
|
+
## Going further
|
|
201
|
+
|
|
202
|
+
The following deep dives are forthcoming under `docs/`:
|
|
203
|
+
|
|
204
|
+
- `docs/lifespan.md` — wiring `poli_page_lifespan` by hand instead of `setup_poli_page`.
|
|
205
|
+
- `docs/async.md` — calling the sync client from `async def` routes via `run_in_threadpool`, and the path to the native `AsyncPoliPage`.
|
|
206
|
+
- `docs/testing.md` — overriding `get_poli_page_client` with `app.dependency_overrides`, and the `TestClient` context-manager requirement.
|
|
207
|
+
- `docs/errors.md` — the full status mapping the global exception handler applies.
|
|
208
|
+
- `docs/responses.md` — RFC 5987 filename encoding, `inline=True`, and streaming responses.
|
|
209
|
+
|
|
210
|
+
## Compatibility
|
|
211
|
+
|
|
212
|
+
| Package version | `poli-page` SDK | FastAPI | Python |
|
|
213
|
+
| --------------- | --------------- | ---------------------- | ------------------- |
|
|
214
|
+
| 0.13.x | 0.13.x | `^0.100`, `^0.110` | 3.11, 3.12, 3.13 |
|
|
215
|
+
|
|
216
|
+
Tested against the FastAPI versions listed above; other 0.x releases in that range are expected to work. The package shares its major.minor with the Poli Page API and requires the SDK of the same minor: `poli-page>=0.13,<0.14`.
|
|
217
|
+
|
|
218
|
+
## Contributing
|
|
219
|
+
|
|
220
|
+
Run the checks CI runs from the repository root: `uv sync --all-extras`, then `uv run ruff check .`, `uv run ruff format --check .`, `uv run mypy src tests example-app/tests` and `uv run pytest tests/unit`.
|
|
221
|
+
|
|
222
|
+
### Contract tests
|
|
223
|
+
|
|
224
|
+
`example-app/tests/test_contract.py` runs the integration cases (`kind: "impl"`) of the [Poli Page API contract](https://github.com/poli-page/api-contract) against the example app: a local server plays the API, the app's SDK points at it through `POLI_PAGE_BASE_URL`, and FastAPI's `TestClient` checks each answer. CI runs them against the contract version pinned in `.github/workflows/ci.yml`. Locally:
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
cd example-app
|
|
228
|
+
uv sync
|
|
229
|
+
POLI_CONTRACT=<path to contract.json> uv run pytest
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Without `POLI_CONTRACT` the test is skipped (in CI it fails). `example-app/tests/contract-skip.json` lists the cases allowed to fail, each with its reason.
|
|
233
|
+
|
|
234
|
+
## License
|
|
235
|
+
|
|
236
|
+
Released under the MIT License — see [LICENSE](https://github.com/poli-page/fastapi/blob/main/LICENSE).
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.21"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "poli-page-fastapi"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "FastAPI integration for the Poli Page PDF rendering API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
authors = [{ name = "Poli Page" }]
|
|
13
|
+
keywords = ["pdf", "html", "template", "rendering", "poli-page", "fastapi", "starlette"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Environment :: Web Environment",
|
|
17
|
+
"Framework :: FastAPI",
|
|
18
|
+
"Framework :: AsyncIO",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"License :: OSI Approved :: MIT License",
|
|
21
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"fastapi>=0.100,<1.0",
|
|
30
|
+
"anyio>=3.7",
|
|
31
|
+
"pydantic>=2.0,<3",
|
|
32
|
+
"pydantic-settings>=2.0,<3",
|
|
33
|
+
"poli-page>=0.13,<0.14",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.optional-dependencies]
|
|
37
|
+
dev = [
|
|
38
|
+
"pytest>=8",
|
|
39
|
+
"pytest-asyncio>=0.23",
|
|
40
|
+
"pytest-mock>=3.12",
|
|
41
|
+
"httpx>=0.25",
|
|
42
|
+
"ruff>=0.6",
|
|
43
|
+
"mypy>=1.10",
|
|
44
|
+
"respx>=0.21",
|
|
45
|
+
"python-dotenv>=1.0",
|
|
46
|
+
"build>=1",
|
|
47
|
+
"twine>=7",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
[project.urls]
|
|
51
|
+
Homepage = "https://poli.page"
|
|
52
|
+
Documentation = "https://docs.poli.page/reference/sdk/"
|
|
53
|
+
Source = "https://github.com/poli-page/fastapi"
|
|
54
|
+
Issues = "https://github.com/poli-page/fastapi/issues"
|
|
55
|
+
Changelog = "https://github.com/poli-page/fastapi/blob/main/CHANGELOG.md"
|
|
56
|
+
Release-Notes = "https://github.com/poli-page/fastapi/releases"
|
|
57
|
+
|
|
58
|
+
[tool.hatch.version]
|
|
59
|
+
source = "regex"
|
|
60
|
+
path = "src/poli_page_fastapi/_version.py"
|
|
61
|
+
pattern = '__version__ = "(?P<version>[^"]+)"'
|
|
62
|
+
|
|
63
|
+
[tool.hatch.build.targets.wheel]
|
|
64
|
+
packages = ["src/poli_page_fastapi"]
|
|
65
|
+
|
|
66
|
+
[tool.hatch.build.targets.sdist]
|
|
67
|
+
# The sdist ships the library only: no tests, example app or repo tooling.
|
|
68
|
+
include = [
|
|
69
|
+
"/src",
|
|
70
|
+
"/README.md",
|
|
71
|
+
"/CHANGELOG.md",
|
|
72
|
+
"/LICENSE",
|
|
73
|
+
"/pyproject.toml",
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
[tool.ruff]
|
|
77
|
+
line-length = 100
|
|
78
|
+
target-version = "py311"
|
|
79
|
+
|
|
80
|
+
[tool.ruff.lint]
|
|
81
|
+
select = ["E", "F", "W", "I", "B", "UP", "RUF", "SIM"]
|
|
82
|
+
|
|
83
|
+
[tool.ruff.lint.per-file-ignores]
|
|
84
|
+
"tests/**/*.py" = ["B017"]
|
|
85
|
+
"example-app/**/*.py" = ["E501"]
|
|
86
|
+
|
|
87
|
+
[tool.mypy]
|
|
88
|
+
python_version = "3.11"
|
|
89
|
+
strict = true
|
|
90
|
+
files = ["src", "tests", "example-app/tests"]
|
|
91
|
+
# The contract test imports the example app's `main` module.
|
|
92
|
+
mypy_path = "example-app"
|
|
93
|
+
plugins = ["pydantic.mypy"]
|
|
94
|
+
|
|
95
|
+
[[tool.mypy.overrides]]
|
|
96
|
+
module = "tests.*"
|
|
97
|
+
disallow_untyped_decorators = false
|
|
98
|
+
|
|
99
|
+
[tool.pytest.ini_options]
|
|
100
|
+
asyncio_mode = "auto"
|
|
101
|
+
python_files = ["test_*.py"]
|
|
102
|
+
testpaths = ["tests"]
|
|
103
|
+
markers = ["integration: hits the live API; requires POLI_PAGE_API_KEY"]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""FastAPI integration for the Poli Page PDF rendering SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from poli_page_fastapi._version import __version__
|
|
6
|
+
from poli_page_fastapi.dependencies import PoliPageDependency, get_poli_page_client
|
|
7
|
+
from poli_page_fastapi.exceptions import poli_page_exception_handler
|
|
8
|
+
from poli_page_fastapi.lifespan import poli_page_lifespan
|
|
9
|
+
from poli_page_fastapi.responses import (
|
|
10
|
+
DocumentRedirectResponse,
|
|
11
|
+
PdfResponse,
|
|
12
|
+
PdfStreamResponse,
|
|
13
|
+
PreviewResponse,
|
|
14
|
+
)
|
|
15
|
+
from poli_page_fastapi.settings import PoliPageSettings
|
|
16
|
+
from poli_page_fastapi.setup import setup_poli_page
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"DocumentRedirectResponse",
|
|
20
|
+
"PdfResponse",
|
|
21
|
+
"PdfStreamResponse",
|
|
22
|
+
"PoliPageDependency",
|
|
23
|
+
"PoliPageSettings",
|
|
24
|
+
"PreviewResponse",
|
|
25
|
+
"__version__",
|
|
26
|
+
"get_poli_page_client",
|
|
27
|
+
"poli_page_exception_handler",
|
|
28
|
+
"poli_page_lifespan",
|
|
29
|
+
"setup_poli_page",
|
|
30
|
+
]
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Internal: RFC 6266 / RFC 8187 (ex-5987) Content-Disposition encoding.
|
|
2
|
+
|
|
3
|
+
Same contract as the other Poli Page framework integrations (django-poli-page's
|
|
4
|
+
``_build_disposition`` is the reference): control characters are stripped, ``\\``
|
|
5
|
+
and ``"`` are escaped as quoted-pairs, and non-ASCII filenames get the dual
|
|
6
|
+
``filename="<ascii-fallback>"; filename*=UTF-8''<percent-encoded>`` notation.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from urllib.parse import quote
|
|
13
|
+
|
|
14
|
+
# C0 controls (incl. TAB, CR, LF), DEL and C1 controls. None of them belong in a
|
|
15
|
+
# filename, and CR/LF would split the header (response splitting).
|
|
16
|
+
_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def build_content_disposition(filename: str, *, inline: bool = False) -> str:
|
|
20
|
+
"""Return a Content-Disposition header value with correct filename encoding.
|
|
21
|
+
|
|
22
|
+
ASCII filenames: ``attachment; filename="..."``.
|
|
23
|
+
Non-ASCII filenames: dual form —
|
|
24
|
+
``attachment; filename="<ascii-fallback>"; filename*=UTF-8''<percent-encoded>``.
|
|
25
|
+
"""
|
|
26
|
+
disposition = "inline" if inline else "attachment"
|
|
27
|
+
clean = _CONTROL_CHARS.sub("", filename)
|
|
28
|
+
if clean.isascii():
|
|
29
|
+
return f'{disposition}; filename="{_quoted_string_content(clean)}"'
|
|
30
|
+
ascii_fallback = clean.encode("ascii", "replace").decode("ascii")
|
|
31
|
+
encoded = quote(clean, safe="")
|
|
32
|
+
return (
|
|
33
|
+
f'{disposition}; filename="{_quoted_string_content(ascii_fallback)}"; '
|
|
34
|
+
f"filename*=UTF-8''{encoded}"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _quoted_string_content(value: str) -> str:
|
|
39
|
+
"""Escape ``\\`` and ``"`` as quoted-pairs (RFC 9110 §5.6.4)."""
|
|
40
|
+
return value.replace("\\", "\\\\").replace('"', '\\"')
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.13.0"
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""FastAPI dependency factory and class for the Poli Page SDK client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from poli_page import PoliPage
|
|
9
|
+
|
|
10
|
+
from poli_page_fastapi.settings import PoliPageSettings
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _settings_to_kwargs(settings: PoliPageSettings) -> dict[str, Any]:
|
|
14
|
+
kwargs: dict[str, Any] = {}
|
|
15
|
+
if settings.api_key is not None:
|
|
16
|
+
kwargs["api_key"] = settings.api_key
|
|
17
|
+
if settings.base_url is not None:
|
|
18
|
+
kwargs["base_url"] = settings.base_url
|
|
19
|
+
if settings.timeout is not None:
|
|
20
|
+
kwargs["timeout"] = settings.timeout
|
|
21
|
+
if settings.max_retries is not None:
|
|
22
|
+
kwargs["max_retries"] = settings.max_retries
|
|
23
|
+
if settings.retry_delay is not None:
|
|
24
|
+
kwargs["retry_delay"] = settings.retry_delay
|
|
25
|
+
return kwargs
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@lru_cache(maxsize=1)
|
|
29
|
+
def get_poli_page_client() -> PoliPage:
|
|
30
|
+
"""Return the process-wide memoised PoliPage client.
|
|
31
|
+
|
|
32
|
+
Used as `Depends(get_poli_page_client)` in route signatures. The lru_cache
|
|
33
|
+
decorator guarantees one instance per process; to inject a mock in tests,
|
|
34
|
+
use `app.dependency_overrides[get_poli_page_client] = lambda: mock`.
|
|
35
|
+
"""
|
|
36
|
+
settings = PoliPageSettings()
|
|
37
|
+
return PoliPage(**_settings_to_kwargs(settings))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class PoliPageDependency:
|
|
41
|
+
"""Callable dependency that builds a per-instance client.
|
|
42
|
+
|
|
43
|
+
Use when you want explicit settings or a per-router client distinct
|
|
44
|
+
from the global memo. Each instance memoises its own client.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
*,
|
|
50
|
+
settings: PoliPageSettings | None = None,
|
|
51
|
+
client: PoliPage | None = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
self._settings = settings
|
|
54
|
+
self._cached_client: PoliPage | None = client
|
|
55
|
+
|
|
56
|
+
def __call__(self) -> PoliPage:
|
|
57
|
+
if self._cached_client is not None:
|
|
58
|
+
return self._cached_client
|
|
59
|
+
settings = self._settings or PoliPageSettings()
|
|
60
|
+
self._cached_client = PoliPage(**_settings_to_kwargs(settings))
|
|
61
|
+
return self._cached_client
|
|
62
|
+
|
|
63
|
+
def close(self) -> None:
|
|
64
|
+
"""Close the underlying SDK client and clear the cache."""
|
|
65
|
+
if self._cached_client is not None:
|
|
66
|
+
self._cached_client.close()
|
|
67
|
+
self._cached_client = None
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Exception handler answering a `PoliPageError` as JSON.
|
|
2
|
+
|
|
3
|
+
`setup_poli_page(app)` registers it by default. To register it yourself:
|
|
4
|
+
|
|
5
|
+
from poli_page import PoliPageError
|
|
6
|
+
from poli_page_fastapi import poli_page_exception_handler
|
|
7
|
+
|
|
8
|
+
app.add_exception_handler(PoliPageError, poli_page_exception_handler)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from fastapi import Request
|
|
14
|
+
from fastapi.responses import JSONResponse
|
|
15
|
+
from poli_page import PoliPageError
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def poli_page_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
|
19
|
+
"""Answer a `PoliPageError` with its `to_payload()` body.
|
|
20
|
+
|
|
21
|
+
Body: exactly `exc.to_payload()`, `{code, message, status, requestId}` (camelCase
|
|
22
|
+
on the wire, `null` when unknown). Status: the payload's `status` (the API status,
|
|
23
|
+
503 for `network_error`, 504 for `timeout`, 502 for `invalid_response`), or 500 when
|
|
24
|
+
it is `null` (`io_error`, `invalid_options`, a `DOWNLOAD_FAILED` with no storage
|
|
25
|
+
status).
|
|
26
|
+
|
|
27
|
+
Any other exception is re-raised, so the application's own handling applies.
|
|
28
|
+
"""
|
|
29
|
+
if not isinstance(exc, PoliPageError):
|
|
30
|
+
raise exc
|
|
31
|
+
payload = exc.to_payload()
|
|
32
|
+
status = payload["status"]
|
|
33
|
+
return JSONResponse(
|
|
34
|
+
status_code=status if isinstance(status, int) else 500,
|
|
35
|
+
content=payload,
|
|
36
|
+
headers={"Cache-Control": "no-store, private"},
|
|
37
|
+
)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""ASGI lifespan helper: warm the client at startup, close at shutdown."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator
|
|
6
|
+
from contextlib import asynccontextmanager
|
|
7
|
+
|
|
8
|
+
from fastapi import FastAPI
|
|
9
|
+
|
|
10
|
+
from poli_page_fastapi.dependencies import get_poli_page_client
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@asynccontextmanager
|
|
14
|
+
async def poli_page_lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
15
|
+
"""ASGI lifespan that warms the Poli Page client on startup and closes
|
|
16
|
+
it on shutdown.
|
|
17
|
+
|
|
18
|
+
Usage:
|
|
19
|
+
|
|
20
|
+
app = FastAPI(lifespan=poli_page_lifespan)
|
|
21
|
+
"""
|
|
22
|
+
client = get_poli_page_client()
|
|
23
|
+
try:
|
|
24
|
+
yield
|
|
25
|
+
finally:
|
|
26
|
+
client.close()
|
|
27
|
+
get_poli_page_client.cache_clear()
|
|
File without changes
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Response helpers — Starlette response subclasses with the right headers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator, Iterator
|
|
6
|
+
from contextlib import AbstractContextManager
|
|
7
|
+
|
|
8
|
+
import anyio
|
|
9
|
+
import anyio.to_thread
|
|
10
|
+
from starlette.background import BackgroundTask
|
|
11
|
+
from starlette.responses import Response, StreamingResponse
|
|
12
|
+
from starlette.types import Receive, Scope, Send
|
|
13
|
+
|
|
14
|
+
from poli_page_fastapi._headers import build_content_disposition
|
|
15
|
+
|
|
16
|
+
_PDF_DEFAULT_HEADERS = {
|
|
17
|
+
"Cache-Control": "no-store, private",
|
|
18
|
+
"X-Content-Type-Options": "nosniff",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class PdfResponse(Response):
|
|
23
|
+
"""A PDF response with correct Content-Type, Content-Disposition, Cache-Control."""
|
|
24
|
+
|
|
25
|
+
media_type = "application/pdf"
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
content: bytes,
|
|
30
|
+
*,
|
|
31
|
+
status_code: int = 200,
|
|
32
|
+
filename: str = "document.pdf",
|
|
33
|
+
inline: bool = False,
|
|
34
|
+
background: BackgroundTask | None = None,
|
|
35
|
+
headers: dict[str, str] | None = None,
|
|
36
|
+
) -> None:
|
|
37
|
+
# Why: status_code is also exposed so FastAPI's OpenAPI generator can
|
|
38
|
+
# discover the default response status when this class is used as
|
|
39
|
+
# `response_class=PdfResponse` (otherwise /openapi.json returns 500
|
|
40
|
+
# — UnboundLocalError in fastapi/openapi/utils.py).
|
|
41
|
+
merged: dict[str, str] = dict(headers or {})
|
|
42
|
+
merged["Content-Disposition"] = build_content_disposition(filename, inline=inline)
|
|
43
|
+
for k, v in _PDF_DEFAULT_HEADERS.items():
|
|
44
|
+
merged.setdefault(k, v)
|
|
45
|
+
super().__init__(
|
|
46
|
+
content=content,
|
|
47
|
+
status_code=status_code,
|
|
48
|
+
media_type="application/pdf",
|
|
49
|
+
headers=merged,
|
|
50
|
+
background=background,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _OpenedStream:
|
|
55
|
+
"""The chunks of an SDK stream entered at once; exhausting them, or an error, exits it."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, stream: AbstractContextManager[Iterator[bytes]]) -> None:
|
|
58
|
+
self._stream = stream
|
|
59
|
+
self._chunks = iter(stream.__enter__())
|
|
60
|
+
self._open = True
|
|
61
|
+
|
|
62
|
+
def __iter__(self) -> Iterator[bytes]:
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
def __next__(self) -> bytes:
|
|
66
|
+
try:
|
|
67
|
+
return next(self._chunks)
|
|
68
|
+
except BaseException:
|
|
69
|
+
self.close()
|
|
70
|
+
raise
|
|
71
|
+
|
|
72
|
+
def close(self) -> None:
|
|
73
|
+
if self._open:
|
|
74
|
+
self._open = False
|
|
75
|
+
self._stream.__exit__(None, None, None)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class PdfStreamResponse(StreamingResponse):
|
|
79
|
+
"""A streamed PDF response.
|
|
80
|
+
|
|
81
|
+
Pass the SDK's stream as is: `PdfStreamResponse(client.render.pdf_stream(input))`.
|
|
82
|
+
The render and the download start here, in the route, so a `PoliPageError` raises
|
|
83
|
+
before the response starts and reaches the error handler. The stream is closed when
|
|
84
|
+
the response ends: read to the end, failed, or the client disconnected, and before a
|
|
85
|
+
`background` task runs. A response built and never sent leaves it to the garbage
|
|
86
|
+
collector.
|
|
87
|
+
|
|
88
|
+
Opening the stream does the render and the download's first request synchronously:
|
|
89
|
+
build the response in a `def` route (FastAPI runs it in its threadpool), or in
|
|
90
|
+
`run_in_threadpool` from an `async def` route.
|
|
91
|
+
|
|
92
|
+
An iterator of bytes (sync or async) is streamed as given: an error it raises comes
|
|
93
|
+
after the 200 has been sent.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
media_type = "application/pdf"
|
|
97
|
+
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
content: AbstractContextManager[Iterator[bytes]] | Iterator[bytes] | AsyncIterator[bytes],
|
|
101
|
+
*,
|
|
102
|
+
status_code: int = 200,
|
|
103
|
+
filename: str = "document.pdf",
|
|
104
|
+
inline: bool = False,
|
|
105
|
+
background: BackgroundTask | None = None,
|
|
106
|
+
headers: dict[str, str] | None = None,
|
|
107
|
+
) -> None:
|
|
108
|
+
merged: dict[str, str] = dict(headers or {})
|
|
109
|
+
merged["Content-Disposition"] = build_content_disposition(filename, inline=inline)
|
|
110
|
+
for k, v in _PDF_DEFAULT_HEADERS.items():
|
|
111
|
+
merged.setdefault(k, v)
|
|
112
|
+
self._opened: _OpenedStream | None = None
|
|
113
|
+
if isinstance(content, AbstractContextManager):
|
|
114
|
+
content = self._opened = _OpenedStream(content)
|
|
115
|
+
super().__init__(
|
|
116
|
+
content=content,
|
|
117
|
+
status_code=status_code,
|
|
118
|
+
media_type="application/pdf",
|
|
119
|
+
headers=merged,
|
|
120
|
+
background=background,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
124
|
+
if self._opened is None:
|
|
125
|
+
await super().__call__(scope, receive, send)
|
|
126
|
+
return
|
|
127
|
+
# Why: Starlette runs the background task inside __call__, after the body. Run
|
|
128
|
+
# it here instead, once the SDK stream is closed, so the stream's connection
|
|
129
|
+
# does not stay open for as long as the task runs.
|
|
130
|
+
background = self.background
|
|
131
|
+
self.background = None
|
|
132
|
+
try:
|
|
133
|
+
await super().__call__(scope, receive, send)
|
|
134
|
+
finally:
|
|
135
|
+
self.background = background
|
|
136
|
+
# Starlette never closes a sync iterator: on a client disconnect it cancels
|
|
137
|
+
# the send (ASGI < 2.4) or raises ClientDisconnect (2.4+). Close the SDK
|
|
138
|
+
# stream here, shielded from that cancellation, so its connection returns.
|
|
139
|
+
with anyio.CancelScope(shield=True):
|
|
140
|
+
await anyio.to_thread.run_sync(self._opened.close)
|
|
141
|
+
# Starlette's own rule: the task runs when the response returns, a disconnect
|
|
142
|
+
# message included, and not when it raises (ClientDisconnect on ASGI 2.4+).
|
|
143
|
+
if background is not None:
|
|
144
|
+
await background()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class PreviewResponse(Response):
|
|
148
|
+
"""An HTML preview response — text/html; charset=utf-8."""
|
|
149
|
+
|
|
150
|
+
media_type = "text/html; charset=utf-8"
|
|
151
|
+
|
|
152
|
+
def __init__(
|
|
153
|
+
self,
|
|
154
|
+
content: str,
|
|
155
|
+
*,
|
|
156
|
+
status_code: int = 200,
|
|
157
|
+
background: BackgroundTask | None = None,
|
|
158
|
+
headers: dict[str, str] | None = None,
|
|
159
|
+
) -> None:
|
|
160
|
+
merged: dict[str, str] = dict(headers or {})
|
|
161
|
+
merged.setdefault("Cache-Control", "no-store, private")
|
|
162
|
+
merged.setdefault("X-Content-Type-Options", "nosniff")
|
|
163
|
+
super().__init__(
|
|
164
|
+
content=content,
|
|
165
|
+
status_code=status_code,
|
|
166
|
+
media_type="text/html; charset=utf-8",
|
|
167
|
+
headers=merged,
|
|
168
|
+
background=background,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class DocumentRedirectResponse(Response):
|
|
173
|
+
"""A 302 (or 308 if permanent=True) redirect to a document's presigned URL."""
|
|
174
|
+
|
|
175
|
+
def __init__(
|
|
176
|
+
self,
|
|
177
|
+
url: str,
|
|
178
|
+
*,
|
|
179
|
+
permanent: bool = False,
|
|
180
|
+
background: BackgroundTask | None = None,
|
|
181
|
+
headers: dict[str, str] | None = None,
|
|
182
|
+
) -> None:
|
|
183
|
+
merged: dict[str, str] = dict(headers or {})
|
|
184
|
+
merged["Location"] = url
|
|
185
|
+
merged.setdefault("Cache-Control", "no-store, private")
|
|
186
|
+
status_code = 308 if permanent else 302
|
|
187
|
+
super().__init__(
|
|
188
|
+
content=b"",
|
|
189
|
+
status_code=status_code,
|
|
190
|
+
headers=merged,
|
|
191
|
+
background=background,
|
|
192
|
+
)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Pydantic-settings reader for POLI_PAGE_* env vars."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from pydantic import Field, field_validator, model_validator
|
|
10
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
# pp_{environment}_{32 lowercase hex}, the SDK contract's full-key format. It only
|
|
15
|
+
# drives a startup warning: the API is the authority on keys, so a mismatch never
|
|
16
|
+
# stops the client.
|
|
17
|
+
_API_KEY_RE = re.compile(r"pp_(?=[a-z][a-z0-9-]{0,19}_)[a-z][a-z0-9]*(?:-[a-z0-9]+)*_[0-9a-f]{32}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _warn_if_malformed(key: str) -> None:
|
|
21
|
+
if not _API_KEY_RE.fullmatch(key):
|
|
22
|
+
# No part of the key reaches the log: even a pp_{environment}_ prefix can
|
|
23
|
+
# be a pasted secret fragment.
|
|
24
|
+
logger.warning(
|
|
25
|
+
"POLI_PAGE_API_KEY does not match the key format "
|
|
26
|
+
"pp_{environment}_{32 lowercase hex characters}; starting anyway, "
|
|
27
|
+
"the Poli Page API decides whether the key is valid."
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PoliPageSettings(BaseSettings):
|
|
32
|
+
"""Pydantic-settings reader for POLI_PAGE_* env vars.
|
|
33
|
+
|
|
34
|
+
Maps one-to-one with the SDK's PoliPage(__init__) kwargs. Unset values
|
|
35
|
+
are left as None so the SDK applies its own defaults — we never duplicate
|
|
36
|
+
default literals between SDK and integration.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
model_config = SettingsConfigDict(
|
|
40
|
+
env_prefix="POLI_PAGE_",
|
|
41
|
+
env_file=None,
|
|
42
|
+
case_sensitive=False,
|
|
43
|
+
extra="ignore",
|
|
44
|
+
populate_by_name=True,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
api_key: str | None = Field(default=None, alias="POLI_PAGE_API_KEY")
|
|
48
|
+
base_url: str | None = Field(default=None, alias="POLI_PAGE_BASE_URL")
|
|
49
|
+
timeout: float | None = Field(default=None, alias="POLI_PAGE_TIMEOUT")
|
|
50
|
+
max_retries: int | None = Field(default=None, alias="POLI_PAGE_MAX_RETRIES")
|
|
51
|
+
retry_delay: float | None = Field(default=None, alias="POLI_PAGE_RETRY_DELAY")
|
|
52
|
+
|
|
53
|
+
@field_validator("api_key")
|
|
54
|
+
@classmethod
|
|
55
|
+
def _validate_api_key_shape(cls, v: str | None) -> str | None:
|
|
56
|
+
if v is None or v == "":
|
|
57
|
+
return None
|
|
58
|
+
_warn_if_malformed(v)
|
|
59
|
+
return v
|
|
60
|
+
|
|
61
|
+
@model_validator(mode="after")
|
|
62
|
+
def _validate_env_fallback_key(self) -> PoliPageSettings:
|
|
63
|
+
# With no api_key (e.g. an explicit None or "" that overrides the env var),
|
|
64
|
+
# the client is built without one and the SDK reads POLI_PAGE_API_KEY itself.
|
|
65
|
+
if self.api_key is None:
|
|
66
|
+
env_key = os.environ.get("POLI_PAGE_API_KEY")
|
|
67
|
+
if env_key:
|
|
68
|
+
_warn_if_malformed(env_key)
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
@field_validator("timeout")
|
|
72
|
+
@classmethod
|
|
73
|
+
def _validate_timeout(cls, v: float | None) -> float | None:
|
|
74
|
+
if v is not None and not (0 < v <= 600):
|
|
75
|
+
raise ValueError("POLI_PAGE_TIMEOUT must be > 0 and <= 600 seconds.")
|
|
76
|
+
return v
|
|
77
|
+
|
|
78
|
+
@field_validator("max_retries")
|
|
79
|
+
@classmethod
|
|
80
|
+
def _validate_max_retries(cls, v: int | None) -> int | None:
|
|
81
|
+
if v is not None and not (0 <= v <= 10):
|
|
82
|
+
raise ValueError("POLI_PAGE_MAX_RETRIES must be between 0 and 10.")
|
|
83
|
+
return v
|
|
84
|
+
|
|
85
|
+
@field_validator("retry_delay")
|
|
86
|
+
@classmethod
|
|
87
|
+
def _validate_retry_delay(cls, v: float | None) -> float | None:
|
|
88
|
+
if v is not None and not (0 <= v <= 30):
|
|
89
|
+
raise ValueError("POLI_PAGE_RETRY_DELAY must be between 0 and 30 seconds.")
|
|
90
|
+
return v
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""One call to set up the integration on an app: client lifespan and error handler."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator
|
|
6
|
+
from contextlib import asynccontextmanager
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from fastapi import FastAPI
|
|
10
|
+
from poli_page import PoliPageError
|
|
11
|
+
|
|
12
|
+
from poli_page_fastapi.exceptions import poli_page_exception_handler
|
|
13
|
+
from poli_page_fastapi.lifespan import poli_page_lifespan
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def setup_poli_page(app: FastAPI, *, error_handler: bool = True) -> None:
|
|
17
|
+
"""Set up Poli Page on `app`. Call it once, before the app starts.
|
|
18
|
+
|
|
19
|
+
- Wraps the app's lifespan in `poli_page_lifespan`: the client is built at
|
|
20
|
+
startup and closed at shutdown. The app's own lifespan (or its startup and
|
|
21
|
+
shutdown handlers) still runs, inside it.
|
|
22
|
+
- Registers `poli_page_exception_handler` for `PoliPageError`, unless
|
|
23
|
+
`error_handler=False`: a route that lets a `PoliPageError` through answers
|
|
24
|
+
its `to_payload()` JSON with its status (500 when it has none).
|
|
25
|
+
|
|
26
|
+
Raises `RuntimeError` once the app has started: Starlette copies the exception
|
|
27
|
+
handlers when it builds its middleware stack, on the first ASGI call, so a later
|
|
28
|
+
handler would never run.
|
|
29
|
+
|
|
30
|
+
Usage:
|
|
31
|
+
|
|
32
|
+
app = FastAPI()
|
|
33
|
+
setup_poli_page(app)
|
|
34
|
+
"""
|
|
35
|
+
if app.middleware_stack is not None:
|
|
36
|
+
raise RuntimeError("Call setup_poli_page(app) before the app starts.")
|
|
37
|
+
if error_handler:
|
|
38
|
+
app.add_exception_handler(PoliPageError, poli_page_exception_handler)
|
|
39
|
+
|
|
40
|
+
app_lifespan = app.router.lifespan_context
|
|
41
|
+
|
|
42
|
+
@asynccontextmanager
|
|
43
|
+
async def lifespan(lifespan_app: Any) -> AsyncIterator[Any]:
|
|
44
|
+
async with poli_page_lifespan(lifespan_app), app_lifespan(lifespan_app) as state:
|
|
45
|
+
yield state
|
|
46
|
+
|
|
47
|
+
app.router.lifespan_context = lifespan
|