mizanpage 1.0.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.
- mizanpage-1.0.0/.gitignore +5 -0
- mizanpage-1.0.0/LICENSE +21 -0
- mizanpage-1.0.0/PKG-INFO +66 -0
- mizanpage-1.0.0/README.md +50 -0
- mizanpage-1.0.0/pyproject.toml +27 -0
- mizanpage-1.0.0/src/mizanpage/__init__.py +374 -0
- mizanpage-1.0.0/src/mizanpage/py.typed +0 -0
- mizanpage-1.0.0/tests/test_client.py +153 -0
mizanpage-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Laudelout Studio
|
|
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.
|
mizanpage-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mizanpage
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Client officiel de l'API Mizanpage : générer des PDF depuis vos modèles, en direct ou en file d'attente, et vérifier les webhooks.
|
|
5
|
+
Project-URL: Homepage, https://mizanpage.com
|
|
6
|
+
Project-URL: Documentation, https://mizanpage.com/docs
|
|
7
|
+
Author-email: Laudelout Studio <contact@mizanpage.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api,documents,mizanpage,pdf,templates
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Office/Business
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# mizanpage
|
|
18
|
+
|
|
19
|
+
Client officiel de l'API [Mizanpage](https://mizanpage.com) pour Python 3.9+, sans dépendance.
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install mizanpage
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import os
|
|
27
|
+
from mizanpage import Mizanpage, verify_webhook
|
|
28
|
+
|
|
29
|
+
mizanpage = Mizanpage(os.environ["MIZANPAGE_KEY"])
|
|
30
|
+
|
|
31
|
+
# Le PDF dans la même réponse
|
|
32
|
+
mizanpage.render(
|
|
33
|
+
{"template": "facture", "data": {"values": {"client.nom": "Brasserie Lumen SRL", "facture.total": "7 788,00 €"}}},
|
|
34
|
+
idempotency_key="F-2026-0148",
|
|
35
|
+
).save("facture.pdf")
|
|
36
|
+
|
|
37
|
+
# Sans attendre (POST /v1/renders) : demander, attendre, télécharger
|
|
38
|
+
job, pdf = mizanpage.renders.create_and_wait({"template": "facture", "reference": "C-2041", "data": {"values": values}})
|
|
39
|
+
|
|
40
|
+
# Un webhook reçu : le corps brut, les en-têtes, le secret whsec_…
|
|
41
|
+
event = verify_webhook(raw_body, request.headers, os.environ["MIZANPAGE_WEBHOOK_SECRET"])
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
| Méthode | Route |
|
|
45
|
+
| --- | --- |
|
|
46
|
+
| `render(request, idempotency_key=…)` | `POST /v1/render` |
|
|
47
|
+
| `renders.create / get / wait / download / create_and_wait` | `POST /v1/renders`, `GET /v1/renders/{id}`, `GET /v1/renders/{id}/pdf` |
|
|
48
|
+
| `templates.list(kind=…) / get(ref) / fields(ref)` | `GET /v1/templates`, `GET /v1/templates/{ref}/fields` |
|
|
49
|
+
| `catalogs.list / get / put` | `/v1/catalogs` |
|
|
50
|
+
| `webhooks.list / create / update / delete / test` | `/v1/webhooks` |
|
|
51
|
+
| `pdf.from_html(html, **options) / merge(pdfs) / split(pdf, pages=… \| ranges=… \| every=…)` | `POST /v1/pdf/html`, `/v1/pdf/merge`, `/v1/pdf/split` |
|
|
52
|
+
| `me()` | `GET /v1/me` |
|
|
53
|
+
|
|
54
|
+
Options du client : `base_url`, `organisation` (installation de partenaire), `user=(id, nom)`, `timeout` (secondes), `transport`.
|
|
55
|
+
|
|
56
|
+
Une erreur de l'API lève une `MizanpageError` avec `status`, `code` et `details`. Documentation : https://mizanpage.com/docs/developpeurs. Référence : https://api.mizanpage.com/docs.
|
|
57
|
+
|
|
58
|
+
À utiliser côté serveur : une clé d'API ne va jamais dans un navigateur.
|
|
59
|
+
|
|
60
|
+
## Développer
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
PYTHONPATH=src python3 -m unittest discover -s tests
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Licence MIT.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# mizanpage
|
|
2
|
+
|
|
3
|
+
Client officiel de l'API [Mizanpage](https://mizanpage.com) pour Python 3.9+, sans dépendance.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install mizanpage
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import os
|
|
11
|
+
from mizanpage import Mizanpage, verify_webhook
|
|
12
|
+
|
|
13
|
+
mizanpage = Mizanpage(os.environ["MIZANPAGE_KEY"])
|
|
14
|
+
|
|
15
|
+
# Le PDF dans la même réponse
|
|
16
|
+
mizanpage.render(
|
|
17
|
+
{"template": "facture", "data": {"values": {"client.nom": "Brasserie Lumen SRL", "facture.total": "7 788,00 €"}}},
|
|
18
|
+
idempotency_key="F-2026-0148",
|
|
19
|
+
).save("facture.pdf")
|
|
20
|
+
|
|
21
|
+
# Sans attendre (POST /v1/renders) : demander, attendre, télécharger
|
|
22
|
+
job, pdf = mizanpage.renders.create_and_wait({"template": "facture", "reference": "C-2041", "data": {"values": values}})
|
|
23
|
+
|
|
24
|
+
# Un webhook reçu : le corps brut, les en-têtes, le secret whsec_…
|
|
25
|
+
event = verify_webhook(raw_body, request.headers, os.environ["MIZANPAGE_WEBHOOK_SECRET"])
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
| Méthode | Route |
|
|
29
|
+
| --- | --- |
|
|
30
|
+
| `render(request, idempotency_key=…)` | `POST /v1/render` |
|
|
31
|
+
| `renders.create / get / wait / download / create_and_wait` | `POST /v1/renders`, `GET /v1/renders/{id}`, `GET /v1/renders/{id}/pdf` |
|
|
32
|
+
| `templates.list(kind=…) / get(ref) / fields(ref)` | `GET /v1/templates`, `GET /v1/templates/{ref}/fields` |
|
|
33
|
+
| `catalogs.list / get / put` | `/v1/catalogs` |
|
|
34
|
+
| `webhooks.list / create / update / delete / test` | `/v1/webhooks` |
|
|
35
|
+
| `pdf.from_html(html, **options) / merge(pdfs) / split(pdf, pages=… \| ranges=… \| every=…)` | `POST /v1/pdf/html`, `/v1/pdf/merge`, `/v1/pdf/split` |
|
|
36
|
+
| `me()` | `GET /v1/me` |
|
|
37
|
+
|
|
38
|
+
Options du client : `base_url`, `organisation` (installation de partenaire), `user=(id, nom)`, `timeout` (secondes), `transport`.
|
|
39
|
+
|
|
40
|
+
Une erreur de l'API lève une `MizanpageError` avec `status`, `code` et `details`. Documentation : https://mizanpage.com/docs/developpeurs. Référence : https://api.mizanpage.com/docs.
|
|
41
|
+
|
|
42
|
+
À utiliser côté serveur : une clé d'API ne va jamais dans un navigateur.
|
|
43
|
+
|
|
44
|
+
## Développer
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
PYTHONPATH=src python3 -m unittest discover -s tests
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Licence MIT.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mizanpage"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Client officiel de l'API Mizanpage : générer des PDF depuis vos modèles, en direct ou en file d'attente, et vérifier les webhooks."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
authors = [{ name = "Laudelout Studio", email = "contact@mizanpage.com" }]
|
|
14
|
+
keywords = ["mizanpage", "pdf", "documents", "templates", "api"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Topic :: Office/Business",
|
|
19
|
+
]
|
|
20
|
+
dependencies = []
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://mizanpage.com"
|
|
24
|
+
Documentation = "https://mizanpage.com/docs"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["src/mizanpage"]
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""Official client for the Mizanpage API.
|
|
2
|
+
|
|
3
|
+
- ``client.render()``: the PDF in the same response (``POST /v1/render``).
|
|
4
|
+
- ``client.renders``: asynchronous rendering (``POST /v1/renders``), then
|
|
5
|
+
waiting, polling and downloading.
|
|
6
|
+
- ``client.pdf``: the PDF tools without a template (HTML to PDF, merge, split).
|
|
7
|
+
- ``client.templates``, ``client.catalogs``, ``client.webhooks``,
|
|
8
|
+
``client.me()``: the rest of the integration.
|
|
9
|
+
- ``verify_webhook()``: check the signature of a webhook you received.
|
|
10
|
+
|
|
11
|
+
No dependency: only the Python standard library. Server side only: an API
|
|
12
|
+
key never goes into a browser.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import base64
|
|
18
|
+
import hashlib
|
|
19
|
+
import hmac
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
import time
|
|
23
|
+
import urllib.error
|
|
24
|
+
import urllib.parse
|
|
25
|
+
import urllib.request
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"VERSION",
|
|
31
|
+
"DEFAULT_BASE_URL",
|
|
32
|
+
"Mizanpage",
|
|
33
|
+
"MizanpageError",
|
|
34
|
+
"RenderedPdf",
|
|
35
|
+
"Response",
|
|
36
|
+
"WebhookVerificationError",
|
|
37
|
+
"verify_webhook",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
VERSION = "1.0.0"
|
|
41
|
+
DEFAULT_BASE_URL = "https://api.mizanpage.com"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class MizanpageError(Exception):
|
|
45
|
+
"""An API error: ``status``, a stable ``code``, a readable ``message`` and ``details``."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, status: int, code: str, message: str, details: Optional[Dict[str, Any]] = None):
|
|
48
|
+
super().__init__(message)
|
|
49
|
+
self.status = status
|
|
50
|
+
self.code = code
|
|
51
|
+
self.message = message
|
|
52
|
+
self.details = details or {}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class WebhookVerificationError(Exception):
|
|
56
|
+
"""The webhook signature does not match, or its timestamp is too old."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class Response:
|
|
61
|
+
"""What a transport returns: the status, the headers (lower-case names) and the raw body."""
|
|
62
|
+
|
|
63
|
+
status: int
|
|
64
|
+
headers: Dict[str, str]
|
|
65
|
+
body: bytes
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], Response]
|
|
69
|
+
"""``transport(method, url, headers, body, timeout_seconds) -> Response``. Replace it for tests or a proxy."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class RenderedPdf:
|
|
74
|
+
"""A PDF from ``POST /v1/render`` and what its headers say about it."""
|
|
75
|
+
|
|
76
|
+
pdf: bytes
|
|
77
|
+
generation_id: Optional[str]
|
|
78
|
+
template_id: Optional[str]
|
|
79
|
+
template_version: Optional[int]
|
|
80
|
+
document_id: Optional[str]
|
|
81
|
+
test: bool
|
|
82
|
+
|
|
83
|
+
def save(self, path: str) -> None:
|
|
84
|
+
with open(path, "wb") as file:
|
|
85
|
+
file.write(self.pdf)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def urllib_transport(method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float) -> Response:
|
|
89
|
+
"""The default transport, on ``urllib``."""
|
|
90
|
+
request = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
91
|
+
try:
|
|
92
|
+
with urllib.request.urlopen(request, timeout=timeout) as answer:
|
|
93
|
+
return Response(answer.status, {k.lower(): v for k, v in answer.headers.items()}, answer.read())
|
|
94
|
+
except urllib.error.HTTPError as error:
|
|
95
|
+
return Response(error.code, {k.lower(): v for k, v in error.headers.items()}, error.read())
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _quote(value: str) -> str:
|
|
99
|
+
return urllib.parse.quote(value, safe="")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class Mizanpage:
|
|
103
|
+
"""The client.
|
|
104
|
+
|
|
105
|
+
``api_key``: the workspace key (``mzp_live_…``, ``mzp_test_…``) or an
|
|
106
|
+
installation key (``mzi_…``). ``organisation``: for a partner
|
|
107
|
+
installation, the organisation reference (``X-Mizanpage-Organisation``).
|
|
108
|
+
``user``: ``(id, name)`` of the person in your software the call is made
|
|
109
|
+
for. ``timeout``: seconds per call (60 by default).
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
def __init__(
|
|
113
|
+
self,
|
|
114
|
+
api_key: str,
|
|
115
|
+
*,
|
|
116
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
117
|
+
organisation: Optional[str] = None,
|
|
118
|
+
user: Optional[Tuple[str, Optional[str]]] = None,
|
|
119
|
+
timeout: float = 60.0,
|
|
120
|
+
transport: Optional[Transport] = None,
|
|
121
|
+
):
|
|
122
|
+
if not isinstance(api_key, str) or api_key == "":
|
|
123
|
+
raise ValueError("Mizanpage: api_key is required.")
|
|
124
|
+
self._api_key = api_key
|
|
125
|
+
self._base_url = base_url.rstrip("/")
|
|
126
|
+
self._organisation = organisation
|
|
127
|
+
self._user = user
|
|
128
|
+
self._timeout = timeout
|
|
129
|
+
self._transport = transport or urllib_transport
|
|
130
|
+
self.renders = Renders(self)
|
|
131
|
+
self.templates = Templates(self)
|
|
132
|
+
self.catalogs = Catalogs(self)
|
|
133
|
+
self.webhooks = Webhooks(self)
|
|
134
|
+
self.pdf = PdfTools(self)
|
|
135
|
+
|
|
136
|
+
def render(self, request: Mapping[str, Any], *, idempotency_key: Optional[str] = None) -> RenderedPdf:
|
|
137
|
+
"""The PDF in the same response (``POST /v1/render``)."""
|
|
138
|
+
response = self._request("POST", "/v1/render", {**request, "format": "pdf"}, idempotency_key=idempotency_key)
|
|
139
|
+
template = response.headers.get("x-mizanpage-template")
|
|
140
|
+
match = re.match(r"^([^;]+);version=(\d+)$", template) if template else None
|
|
141
|
+
return RenderedPdf(
|
|
142
|
+
pdf=response.body,
|
|
143
|
+
generation_id=response.headers.get("x-mizanpage-generation"),
|
|
144
|
+
template_id=match.group(1) if match else None,
|
|
145
|
+
template_version=int(match.group(2)) if match else None,
|
|
146
|
+
document_id=response.headers.get("x-mizanpage-document"),
|
|
147
|
+
test=response.headers.get("x-mizanpage-test") == "1",
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
def me(self) -> Dict[str, Any]:
|
|
151
|
+
"""The workspace, the person acting and what the studio offers (``GET /v1/me``)."""
|
|
152
|
+
return self._json("GET", "/v1/me")
|
|
153
|
+
|
|
154
|
+
def _json(self, method: str, path: str, body: Any = None, *, idempotency_key: Optional[str] = None, query: Optional[Mapping[str, Optional[str]]] = None) -> Any:
|
|
155
|
+
response = self._request(method, path, body, idempotency_key=idempotency_key, query=query)
|
|
156
|
+
if response.status == 204 or not response.body:
|
|
157
|
+
return None
|
|
158
|
+
return json.loads(response.body.decode("utf-8"))
|
|
159
|
+
|
|
160
|
+
def _request(self, method: str, path: str, body: Any = None, *, idempotency_key: Optional[str] = None, query: Optional[Mapping[str, Optional[str]]] = None) -> Response:
|
|
161
|
+
headers = {
|
|
162
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
163
|
+
"Accept": "application/json, application/pdf",
|
|
164
|
+
"User-Agent": f"mizanpage-python/{VERSION}",
|
|
165
|
+
}
|
|
166
|
+
data = None
|
|
167
|
+
if body is not None:
|
|
168
|
+
headers["Content-Type"] = "application/json"
|
|
169
|
+
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
170
|
+
if idempotency_key:
|
|
171
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
172
|
+
if self._organisation:
|
|
173
|
+
headers["X-Mizanpage-Organisation"] = self._organisation
|
|
174
|
+
if self._user:
|
|
175
|
+
headers["X-Mizanpage-User"] = self._user[0]
|
|
176
|
+
if len(self._user) > 1 and self._user[1]:
|
|
177
|
+
headers["X-Mizanpage-User-Name"] = self._user[1]
|
|
178
|
+
|
|
179
|
+
url = self._base_url + path
|
|
180
|
+
params = {k: v for k, v in (query or {}).items() if v is not None}
|
|
181
|
+
if params:
|
|
182
|
+
url += "?" + urllib.parse.urlencode(params)
|
|
183
|
+
|
|
184
|
+
response = self._transport(method, url, headers, data, self._timeout)
|
|
185
|
+
if response.status >= 400:
|
|
186
|
+
raise _error_of(response)
|
|
187
|
+
return response
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class Renders:
|
|
191
|
+
def __init__(self, client: Mizanpage):
|
|
192
|
+
self._client = client
|
|
193
|
+
|
|
194
|
+
def create(self, request: Mapping[str, Any], *, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
|
|
195
|
+
"""Ask for a PDF without waiting (``POST /v1/renders``): the answer says ``queued``."""
|
|
196
|
+
return self._client._json("POST", "/v1/renders", {**request, "format": "pdf"}, idempotency_key=idempotency_key)
|
|
197
|
+
|
|
198
|
+
def get(self, render_id: str) -> Dict[str, Any]:
|
|
199
|
+
"""Where the render stands (``GET /v1/renders/{id}``)."""
|
|
200
|
+
return self._client._json("GET", f"/v1/renders/{_quote(render_id)}")
|
|
201
|
+
|
|
202
|
+
def wait(self, render_id: str, *, timeout: float = 120.0, interval: float = 2.0, sleep: Callable[[float], None] = time.sleep) -> Dict[str, Any]:
|
|
203
|
+
"""Wait for the render to finish. Returns the succeeded render; raises ``MizanpageError`` if it failed or the delay ran out."""
|
|
204
|
+
deadline = time.monotonic() + timeout
|
|
205
|
+
interval = max(1.0, interval)
|
|
206
|
+
while True:
|
|
207
|
+
job = self.get(render_id)
|
|
208
|
+
if job.get("status") == "succeeded":
|
|
209
|
+
return job
|
|
210
|
+
if job.get("status") == "failed":
|
|
211
|
+
error = job.get("error") or {}
|
|
212
|
+
raise MizanpageError(422, error.get("code", "render_failed"), error.get("message", "The render failed."), {"render_id": job.get("id")})
|
|
213
|
+
if time.monotonic() + interval > deadline:
|
|
214
|
+
raise MizanpageError(408, "render_timeout", f"Render {job.get('id')} did not finish in time.", {"render_id": job.get("id")})
|
|
215
|
+
sleep(interval)
|
|
216
|
+
|
|
217
|
+
def download(self, render_id: str) -> bytes:
|
|
218
|
+
"""The PDF of a succeeded render, during the hour it is kept."""
|
|
219
|
+
return self._client._request("GET", f"/v1/renders/{_quote(render_id)}/pdf").body
|
|
220
|
+
|
|
221
|
+
def create_and_wait(self, request: Mapping[str, Any], *, idempotency_key: Optional[str] = None, timeout: float = 120.0, interval: float = 2.0, sleep: Callable[[float], None] = time.sleep) -> Tuple[Dict[str, Any], bytes]:
|
|
222
|
+
"""Ask, wait and download: ``(render, pdf)``."""
|
|
223
|
+
created = self.create(request, idempotency_key=idempotency_key)
|
|
224
|
+
job = self.wait(created["id"], timeout=timeout, interval=interval, sleep=sleep)
|
|
225
|
+
return job, self.download(job["id"])
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class PdfTools:
|
|
229
|
+
def __init__(self, client: Mizanpage):
|
|
230
|
+
self._client = client
|
|
231
|
+
|
|
232
|
+
def from_html(self, html: str, *, idempotency_key: Optional[str] = None, **options: Any) -> RenderedPdf:
|
|
233
|
+
"""A complete HTML page to PDF (``POST /v1/pdf/html``), counted as a generated PDF.
|
|
234
|
+
|
|
235
|
+
Options: ``paper`` (``"A4"`` by default, or ``{"width": …, "height": …}`` in mm),
|
|
236
|
+
``landscape``, ``margins`` (mm), ``css_page_size``, ``print_background``.
|
|
237
|
+
CSS, images and fonts must be inside the page (``data:``).
|
|
238
|
+
"""
|
|
239
|
+
response = self._client._request("POST", "/v1/pdf/html", {**options, "html": html}, idempotency_key=idempotency_key)
|
|
240
|
+
return RenderedPdf(
|
|
241
|
+
pdf=response.body,
|
|
242
|
+
generation_id=response.headers.get("x-mizanpage-generation"),
|
|
243
|
+
template_id=None,
|
|
244
|
+
template_version=None,
|
|
245
|
+
document_id=None,
|
|
246
|
+
test=response.headers.get("x-mizanpage-test") == "1",
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
def merge(self, pdfs: List[bytes]) -> bytes:
|
|
250
|
+
"""Join 2 to 20 PDFs into one, in order (``POST /v1/pdf/merge``). Free."""
|
|
251
|
+
return self._client._request("POST", "/v1/pdf/merge", {"pdfs": [base64.b64encode(p).decode("ascii") for p in pdfs]}).body
|
|
252
|
+
|
|
253
|
+
def split(self, pdf: bytes, *, pages: Optional[str] = None, ranges: Optional[List[str]] = None, every: Optional[int] = None) -> bytes:
|
|
254
|
+
"""Extract pages (``POST /v1/pdf/split``). Free. Give one option: ``pages`` (``"1-3,5"``) returns a PDF;
|
|
255
|
+
``ranges`` (``["1-2", "3-"]``) or ``every`` return a ZIP of PDFs (``part-01.pdf``, ``part-02.pdf``…)."""
|
|
256
|
+
body: Dict[str, Any] = {"pdf": base64.b64encode(pdf).decode("ascii")}
|
|
257
|
+
for name, value in (("pages", pages), ("ranges", ranges), ("every", every)):
|
|
258
|
+
if value is not None:
|
|
259
|
+
body[name] = value
|
|
260
|
+
return self._client._request("POST", "/v1/pdf/split", body).body
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class Templates:
|
|
264
|
+
def __init__(self, client: Mizanpage):
|
|
265
|
+
self._client = client
|
|
266
|
+
|
|
267
|
+
def list(self, kind: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
268
|
+
"""The workspace templates, optionally of one kind."""
|
|
269
|
+
return self._client._json("GET", "/v1/templates", query={"kind": kind})["data"]
|
|
270
|
+
|
|
271
|
+
def get(self, ref: str) -> Dict[str, Any]:
|
|
272
|
+
"""A template, by id or ``external_id``."""
|
|
273
|
+
return self._client._json("GET", f"/v1/templates/{_quote(ref)}")
|
|
274
|
+
|
|
275
|
+
def fields(self, ref: str) -> Dict[str, Any]:
|
|
276
|
+
"""The fields to send for this template: those it prints and those the catalog requires."""
|
|
277
|
+
return self._client._json("GET", f"/v1/templates/{_quote(ref)}/fields")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class Catalogs:
|
|
281
|
+
def __init__(self, client: Mizanpage):
|
|
282
|
+
self._client = client
|
|
283
|
+
|
|
284
|
+
def list(self) -> List[Dict[str, Any]]:
|
|
285
|
+
return self._client._json("GET", "/v1/catalogs")["data"]
|
|
286
|
+
|
|
287
|
+
def get(self, kind: str) -> Dict[str, Any]:
|
|
288
|
+
return self._client._json("GET", f"/v1/catalogs/{_quote(kind)}")
|
|
289
|
+
|
|
290
|
+
def put(self, kind: str, catalog: Mapping[str, Any]) -> Dict[str, Any]:
|
|
291
|
+
"""Create or replace the catalog of a document kind."""
|
|
292
|
+
return self._client._json("PUT", f"/v1/catalogs/{_quote(kind)}", dict(catalog))
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class Webhooks:
|
|
296
|
+
def __init__(self, client: Mizanpage):
|
|
297
|
+
self._client = client
|
|
298
|
+
|
|
299
|
+
def list(self) -> List[Dict[str, Any]]:
|
|
300
|
+
return self._client._json("GET", "/v1/webhooks")["data"]
|
|
301
|
+
|
|
302
|
+
def create(self, url: str, *, events: Optional[List[str]] = None, description: Optional[str] = None) -> Dict[str, Any]:
|
|
303
|
+
"""Declare an endpoint. The secret is only shown here: keep it."""
|
|
304
|
+
body: Dict[str, Any] = {"url": url}
|
|
305
|
+
if events is not None:
|
|
306
|
+
body["events"] = events
|
|
307
|
+
if description is not None:
|
|
308
|
+
body["description"] = description
|
|
309
|
+
return self._client._json("POST", "/v1/webhooks", body)
|
|
310
|
+
|
|
311
|
+
def update(self, webhook_id: str, **changes: Any) -> Dict[str, Any]:
|
|
312
|
+
"""Change ``url``, ``events``, ``description`` or ``enabled``."""
|
|
313
|
+
return self._client._json("PATCH", f"/v1/webhooks/{_quote(webhook_id)}", changes)
|
|
314
|
+
|
|
315
|
+
def delete(self, webhook_id: str) -> None:
|
|
316
|
+
self._client._request("DELETE", f"/v1/webhooks/{_quote(webhook_id)}")
|
|
317
|
+
|
|
318
|
+
def test(self, webhook_id: str) -> Dict[str, Any]:
|
|
319
|
+
"""Send a ``webhook.test`` event and say whether it was received."""
|
|
320
|
+
return self._client._json("POST", f"/v1/webhooks/{_quote(webhook_id)}/test")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def verify_webhook(payload: Union[str, bytes], headers: Mapping[str, Any], secret: str, tolerance_seconds: int = 300) -> Dict[str, Any]:
|
|
324
|
+
"""Check a received webhook (Standard Webhooks) and return its event.
|
|
325
|
+
|
|
326
|
+
``payload`` is the raw body, as received. ``headers`` holds
|
|
327
|
+
``webhook-id``, ``webhook-timestamp`` and ``webhook-signature`` (any
|
|
328
|
+
case). A timestamp older than ``tolerance_seconds`` is refused.
|
|
329
|
+
"""
|
|
330
|
+
normalised: Dict[str, str] = {}
|
|
331
|
+
for name, value in headers.items():
|
|
332
|
+
if isinstance(value, (list, tuple)):
|
|
333
|
+
value = value[0] if value else ""
|
|
334
|
+
normalised[str(name).lower()] = str(value)
|
|
335
|
+
|
|
336
|
+
webhook_id = normalised.get("webhook-id", "")
|
|
337
|
+
timestamp = normalised.get("webhook-timestamp", "")
|
|
338
|
+
signatures = normalised.get("webhook-signature", "")
|
|
339
|
+
if not webhook_id or not timestamp or not signatures:
|
|
340
|
+
raise WebhookVerificationError("Missing webhook-id, webhook-timestamp or webhook-signature header.")
|
|
341
|
+
if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > tolerance_seconds:
|
|
342
|
+
raise WebhookVerificationError("Timestamp missing or too old.")
|
|
343
|
+
|
|
344
|
+
raw = secret[len("whsec_"):] if secret.startswith("whsec_") else secret
|
|
345
|
+
try:
|
|
346
|
+
key = base64.b64decode(raw, validate=True)
|
|
347
|
+
except ValueError as error:
|
|
348
|
+
raise WebhookVerificationError("The secret is not valid.") from error
|
|
349
|
+
|
|
350
|
+
body = payload.decode("utf-8") if isinstance(payload, bytes) else payload
|
|
351
|
+
expected = base64.b64encode(hmac.new(key, f"{webhook_id}.{timestamp}.{body}".encode("utf-8"), hashlib.sha256).digest()).decode("ascii")
|
|
352
|
+
|
|
353
|
+
for candidate in signatures.split(" "):
|
|
354
|
+
version, _, signature = candidate.partition(",")
|
|
355
|
+
if version == "v1" and hmac.compare_digest(signature, expected):
|
|
356
|
+
event = json.loads(body)
|
|
357
|
+
if not isinstance(event, dict):
|
|
358
|
+
raise WebhookVerificationError("The body is not a JSON object.")
|
|
359
|
+
return event
|
|
360
|
+
raise WebhookVerificationError("Invalid signature.")
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _error_of(response: Response) -> MizanpageError:
|
|
364
|
+
error: Any = None
|
|
365
|
+
try:
|
|
366
|
+
error = json.loads(response.body.decode("utf-8")).get("error")
|
|
367
|
+
except (ValueError, AttributeError):
|
|
368
|
+
pass
|
|
369
|
+
if not isinstance(error, dict):
|
|
370
|
+
error = {}
|
|
371
|
+
code = error.get("code") if isinstance(error.get("code"), str) else f"http_{response.status}"
|
|
372
|
+
message = error.get("message") if isinstance(error.get("message"), str) else f"HTTP {response.status}"
|
|
373
|
+
details = error.get("details") if isinstance(error.get("details"), dict) else {}
|
|
374
|
+
return MizanpageError(response.status, code, message, details)
|
|
File without changes
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
import unittest
|
|
7
|
+
|
|
8
|
+
from mizanpage import Mizanpage, MizanpageError, Response, WebhookVerificationError, verify_webhook
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class FakeTransport:
|
|
12
|
+
"""Answers from a list and keeps what it was asked."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, *answers):
|
|
15
|
+
self.answers = list(answers)
|
|
16
|
+
self.calls = []
|
|
17
|
+
|
|
18
|
+
def __call__(self, method, url, headers, body, timeout):
|
|
19
|
+
self.calls.append({"method": method, "url": url, "headers": headers, "body": body})
|
|
20
|
+
if not self.answers:
|
|
21
|
+
raise AssertionError("unexpected call " + url)
|
|
22
|
+
return self.answers.pop(0)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def json_answer(status, body, headers=None):
|
|
26
|
+
return Response(status, {"content-type": "application/json", **(headers or {})}, json.dumps(body).encode())
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def pdf_answer(headers=None):
|
|
30
|
+
return Response(200, {"content-type": "application/pdf", **(headers or {})}, b"%PDF")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ClientTest(unittest.TestCase):
|
|
34
|
+
def test_render_sends_the_key_the_body_and_the_options(self):
|
|
35
|
+
transport = FakeTransport(pdf_answer({"x-mizanpage-generation": "gen-1", "x-mizanpage-template": "tpl-1;version=4"}))
|
|
36
|
+
client = Mizanpage("mzp_live_x", base_url="https://api.test/", organisation="org-42", user=("u1", "Ana"), transport=transport)
|
|
37
|
+
result = client.render({"template": "facture", "data": {"values": {"client.nom": "Jean"}}}, idempotency_key="k-1")
|
|
38
|
+
|
|
39
|
+
call = transport.calls[0]
|
|
40
|
+
self.assertEqual(call["url"], "https://api.test/v1/render")
|
|
41
|
+
self.assertEqual(call["method"], "POST")
|
|
42
|
+
self.assertEqual(call["headers"]["Authorization"], "Bearer mzp_live_x")
|
|
43
|
+
self.assertEqual(call["headers"]["Idempotency-Key"], "k-1")
|
|
44
|
+
self.assertEqual(call["headers"]["X-Mizanpage-Organisation"], "org-42")
|
|
45
|
+
self.assertEqual(call["headers"]["X-Mizanpage-User"], "u1")
|
|
46
|
+
self.assertEqual(call["headers"]["X-Mizanpage-User-Name"], "Ana")
|
|
47
|
+
self.assertEqual(json.loads(call["body"]), {"template": "facture", "data": {"values": {"client.nom": "Jean"}}, "format": "pdf"})
|
|
48
|
+
self.assertEqual(result.pdf, b"%PDF")
|
|
49
|
+
self.assertEqual(result.generation_id, "gen-1")
|
|
50
|
+
self.assertEqual(result.template_id, "tpl-1")
|
|
51
|
+
self.assertEqual(result.template_version, 4)
|
|
52
|
+
self.assertFalse(result.test)
|
|
53
|
+
|
|
54
|
+
def test_an_api_error_becomes_a_mizanpage_error(self):
|
|
55
|
+
transport = FakeTransport(json_answer(409, {"error": {"code": "not_published", "message": "Pas publié.", "details": {"template": "x"}}}))
|
|
56
|
+
client = Mizanpage("k", transport=transport)
|
|
57
|
+
with self.assertRaises(MizanpageError) as raised:
|
|
58
|
+
client.render({"template": "x"})
|
|
59
|
+
self.assertEqual(raised.exception.status, 409)
|
|
60
|
+
self.assertEqual(raised.exception.code, "not_published")
|
|
61
|
+
self.assertEqual(raised.exception.message, "Pas publié.")
|
|
62
|
+
self.assertEqual(raised.exception.details, {"template": "x"})
|
|
63
|
+
|
|
64
|
+
def test_an_error_without_json_keeps_the_status(self):
|
|
65
|
+
client = Mizanpage("k", transport=FakeTransport(Response(503, {"retry-after": "5"}, b"busy")))
|
|
66
|
+
with self.assertRaises(MizanpageError) as raised:
|
|
67
|
+
client.me()
|
|
68
|
+
self.assertEqual(raised.exception.code, "http_503")
|
|
69
|
+
|
|
70
|
+
def test_create_and_wait_queues_polls_and_downloads(self):
|
|
71
|
+
job = {"id": "r1", "status": "queued"}
|
|
72
|
+
transport = FakeTransport(
|
|
73
|
+
json_answer(202, job),
|
|
74
|
+
json_answer(200, {**job, "status": "processing"}),
|
|
75
|
+
json_answer(200, {**job, "status": "succeeded"}),
|
|
76
|
+
pdf_answer(),
|
|
77
|
+
)
|
|
78
|
+
client = Mizanpage("k", base_url="https://api.test", transport=transport)
|
|
79
|
+
done, pdf = client.renders.create_and_wait({"template": "facture", "reference": "Ligne 2"}, sleep=lambda s: None)
|
|
80
|
+
|
|
81
|
+
self.assertEqual(done["status"], "succeeded")
|
|
82
|
+
self.assertEqual(pdf, b"%PDF")
|
|
83
|
+
self.assertEqual([c["url"] for c in transport.calls], [
|
|
84
|
+
"https://api.test/v1/renders",
|
|
85
|
+
"https://api.test/v1/renders/r1",
|
|
86
|
+
"https://api.test/v1/renders/r1",
|
|
87
|
+
"https://api.test/v1/renders/r1/pdf",
|
|
88
|
+
])
|
|
89
|
+
self.assertEqual(json.loads(transport.calls[0]["body"])["reference"], "Ligne 2")
|
|
90
|
+
|
|
91
|
+
def test_wait_raises_the_render_error(self):
|
|
92
|
+
transport = FakeTransport(json_answer(200, {"id": "r1", "status": "failed", "error": {"code": "template_archived", "message": "Retiré."}}))
|
|
93
|
+
with self.assertRaises(MizanpageError) as raised:
|
|
94
|
+
Mizanpage("k", transport=transport).renders.wait("r1")
|
|
95
|
+
self.assertEqual(raised.exception.code, "template_archived")
|
|
96
|
+
|
|
97
|
+
def test_templates_list_passes_the_kind_filter(self):
|
|
98
|
+
transport = FakeTransport(json_answer(200, {"data": [{"id": "t1", "kind": "invoice"}]}))
|
|
99
|
+
templates = Mizanpage("k", base_url="https://api.test", transport=transport).templates.list(kind="invoice")
|
|
100
|
+
self.assertEqual(transport.calls[0]["url"], "https://api.test/v1/templates?kind=invoice")
|
|
101
|
+
self.assertEqual(templates[0]["id"], "t1")
|
|
102
|
+
|
|
103
|
+
def test_webhooks_delete_and_path_encoding(self):
|
|
104
|
+
transport = FakeTransport(Response(204, {}, b""))
|
|
105
|
+
Mizanpage("k", base_url="https://api.test", transport=transport).webhooks.delete("a/b")
|
|
106
|
+
self.assertEqual(transport.calls[0]["method"], "DELETE")
|
|
107
|
+
self.assertEqual(transport.calls[0]["url"], "https://api.test/v1/webhooks/a%2Fb")
|
|
108
|
+
|
|
109
|
+
def test_verify_webhook(self):
|
|
110
|
+
key = b"0123456789abcdef0123456789abcdef"
|
|
111
|
+
secret = "whsec_" + base64.b64encode(key).decode()
|
|
112
|
+
body = json.dumps({"id": "evt_1", "type": "render.completed", "data": {"render_id": "r1"}})
|
|
113
|
+
timestamp = str(int(time.time()))
|
|
114
|
+
signature = base64.b64encode(hmac.new(key, f"msg_1.{timestamp}.{body}".encode(), hashlib.sha256).digest()).decode()
|
|
115
|
+
headers = {"Webhook-Id": "msg_1", "webhook-timestamp": timestamp, "webhook-signature": f"v1,{signature}"}
|
|
116
|
+
|
|
117
|
+
self.assertEqual(verify_webhook(body, headers, secret)["type"], "render.completed")
|
|
118
|
+
self.assertEqual(verify_webhook(body.encode(), headers, secret)["type"], "render.completed")
|
|
119
|
+
with self.assertRaises(WebhookVerificationError):
|
|
120
|
+
verify_webhook(body + " ", headers, secret)
|
|
121
|
+
with self.assertRaises(WebhookVerificationError):
|
|
122
|
+
verify_webhook(body, {**headers, "webhook-timestamp": str(int(timestamp) - 3600)}, secret)
|
|
123
|
+
with self.assertRaises(WebhookVerificationError):
|
|
124
|
+
verify_webhook(body, {"webhook-id": "msg_1", "webhook-timestamp": timestamp}, secret)
|
|
125
|
+
|
|
126
|
+
def test_pdf_tools_send_their_bodies(self):
|
|
127
|
+
transport = FakeTransport(
|
|
128
|
+
pdf_answer({"x-mizanpage-generation": "gen-2", "x-mizanpage-test": "1"}),
|
|
129
|
+
pdf_answer(),
|
|
130
|
+
Response(200, {"content-type": "application/zip"}, b"PK"),
|
|
131
|
+
)
|
|
132
|
+
client = Mizanpage("k", base_url="https://api.test", transport=transport)
|
|
133
|
+
html = client.pdf.from_html("<h1>Bon</h1>", paper="A5", margins=15, idempotency_key="h-1")
|
|
134
|
+
client.pdf.merge([b"\x01\x02", b"\xff"])
|
|
135
|
+
zip_file = client.pdf.split(b"\x01\x02\x03", every=1)
|
|
136
|
+
|
|
137
|
+
self.assertEqual(transport.calls[0]["url"], "https://api.test/v1/pdf/html")
|
|
138
|
+
self.assertEqual(transport.calls[0]["headers"]["Idempotency-Key"], "h-1")
|
|
139
|
+
self.assertEqual(json.loads(transport.calls[0]["body"]), {"paper": "A5", "margins": 15, "html": "<h1>Bon</h1>"})
|
|
140
|
+
self.assertEqual(html.generation_id, "gen-2")
|
|
141
|
+
self.assertTrue(html.test)
|
|
142
|
+
self.assertEqual(transport.calls[1]["url"], "https://api.test/v1/pdf/merge")
|
|
143
|
+
self.assertEqual(json.loads(transport.calls[1]["body"]), {"pdfs": ["AQI=", "/w=="]})
|
|
144
|
+
self.assertEqual(json.loads(transport.calls[2]["body"]), {"pdf": "AQID", "every": 1})
|
|
145
|
+
self.assertEqual(zip_file, b"PK")
|
|
146
|
+
|
|
147
|
+
def test_the_key_is_required(self):
|
|
148
|
+
with self.assertRaises(ValueError):
|
|
149
|
+
Mizanpage("")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
if __name__ == "__main__":
|
|
153
|
+
unittest.main()
|