html-css-to-image 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- html_css_to_image/__init__.py +75 -0
- html_css_to_image/_request_mapper.py +198 -0
- html_css_to_image/_response_mapper.py +168 -0
- html_css_to_image/_transport.py +71 -0
- html_css_to_image/_url_builder.py +269 -0
- html_css_to_image/_version.py +8 -0
- html_css_to_image/client.py +317 -0
- html_css_to_image/exceptions.py +21 -0
- html_css_to_image/models.py +600 -0
- html_css_to_image/py.typed +1 -0
- html_css_to_image-0.2.0.dist-info/METADATA +300 -0
- html_css_to_image-0.2.0.dist-info/RECORD +14 -0
- html_css_to_image-0.2.0.dist-info/WHEEL +4 -0
- html_css_to_image-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""Internal construction and signing of HCTI image URLs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import json
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
from typing import Any
|
|
10
|
+
from urllib.parse import quote, quote_plus
|
|
11
|
+
|
|
12
|
+
from ._request_mapper import RequestMapper
|
|
13
|
+
from .models import (
|
|
14
|
+
CreateTemplatedImageRequest,
|
|
15
|
+
CreateUrlImageRequest,
|
|
16
|
+
RenderImageCrop,
|
|
17
|
+
RenderImageCropSpan,
|
|
18
|
+
RenderImageOptions,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class UrlBuilder:
|
|
23
|
+
"""Build unsigned retrieval URLs and HMAC-signed rendering URLs."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, api_id: str, api_key: str, base_url: str) -> None:
|
|
26
|
+
self._api_id = api_id
|
|
27
|
+
self._api_key = api_key
|
|
28
|
+
self._base_url = base_url
|
|
29
|
+
|
|
30
|
+
def image_url(
|
|
31
|
+
self,
|
|
32
|
+
image_id: str,
|
|
33
|
+
render_options: RenderImageOptions | None,
|
|
34
|
+
) -> str:
|
|
35
|
+
"""Build the retrieval URL for an existing image."""
|
|
36
|
+
|
|
37
|
+
options = render_options or RenderImageOptions()
|
|
38
|
+
path = f"{self._base_url}/v1/image/{quote(image_id, safe='')}"
|
|
39
|
+
if options.format is not None:
|
|
40
|
+
path += f".{options.format}"
|
|
41
|
+
query = self._form_encode(self._render_option_pairs(options))
|
|
42
|
+
return f"{path}?{query}" if query else path
|
|
43
|
+
|
|
44
|
+
def templated_image_url(
|
|
45
|
+
self,
|
|
46
|
+
request: CreateTemplatedImageRequest,
|
|
47
|
+
render_options: RenderImageOptions | None,
|
|
48
|
+
) -> str:
|
|
49
|
+
"""Build an HMAC-signed saved-template rendering URL."""
|
|
50
|
+
|
|
51
|
+
pairs: list[tuple[str, str]] = []
|
|
52
|
+
if request.template_version:
|
|
53
|
+
pairs.append(("template_version", str(request.template_version)))
|
|
54
|
+
|
|
55
|
+
for key in sorted(request.template_values):
|
|
56
|
+
value = request.template_values[key]
|
|
57
|
+
if value is None:
|
|
58
|
+
continue
|
|
59
|
+
if isinstance(value, (Mapping, list, tuple)):
|
|
60
|
+
encoded_value = json.dumps(
|
|
61
|
+
value,
|
|
62
|
+
separators=(",", ":"),
|
|
63
|
+
ensure_ascii=False,
|
|
64
|
+
)
|
|
65
|
+
else:
|
|
66
|
+
encoded_value = self._javascript_string(value)
|
|
67
|
+
pairs.append((key, encoded_value))
|
|
68
|
+
|
|
69
|
+
options = render_options or RenderImageOptions()
|
|
70
|
+
pairs.extend(
|
|
71
|
+
self._render_option_pairs(
|
|
72
|
+
options,
|
|
73
|
+
reserved_keys=set(request.template_values),
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
query = self._form_encode(pairs)
|
|
77
|
+
token = self._generate_hmac_token(query)
|
|
78
|
+
separator = "?" if query else ""
|
|
79
|
+
format_value = options.format or request.format
|
|
80
|
+
format_path = f"/{format_value}" if format_value is not None else ""
|
|
81
|
+
return (
|
|
82
|
+
f"{self._base_url}/v1/image/{request.template_id}/{token}"
|
|
83
|
+
f"{format_path}{separator}{query}"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def create_and_render_url(
|
|
87
|
+
self,
|
|
88
|
+
request: CreateUrlImageRequest,
|
|
89
|
+
render_options: RenderImageOptions | None,
|
|
90
|
+
) -> str:
|
|
91
|
+
"""Build an HMAC-signed create-and-render URL."""
|
|
92
|
+
|
|
93
|
+
pairs: list[tuple[str, str]] = [("url", request.url)]
|
|
94
|
+
payload = RequestMapper.common_payload(request, include_dedupe=False)
|
|
95
|
+
payload.update(
|
|
96
|
+
{
|
|
97
|
+
"css": request.css,
|
|
98
|
+
"headers": (
|
|
99
|
+
dict(request.headers) if request.headers is not None else None
|
|
100
|
+
),
|
|
101
|
+
"additional_header_origins": (
|
|
102
|
+
list(request.additional_header_origins)
|
|
103
|
+
if request.additional_header_origins is not None
|
|
104
|
+
else None
|
|
105
|
+
),
|
|
106
|
+
"include_headers_on_subrequests": (
|
|
107
|
+
request.include_headers_on_subrequests
|
|
108
|
+
),
|
|
109
|
+
"identify_as_hcti": request.identify_as_hcti,
|
|
110
|
+
"full_screen": request.full_screen,
|
|
111
|
+
"block_consent_banners": request.block_consent_banners,
|
|
112
|
+
}
|
|
113
|
+
)
|
|
114
|
+
payload.pop("pdf_options", None)
|
|
115
|
+
payload.pop("format", None)
|
|
116
|
+
|
|
117
|
+
for key in sorted(payload):
|
|
118
|
+
value = payload[key]
|
|
119
|
+
if value is None or (value is False and key != "transparent_background"):
|
|
120
|
+
continue
|
|
121
|
+
if key == "headers":
|
|
122
|
+
pairs.extend(
|
|
123
|
+
("headers", f"{name}:{header_value}")
|
|
124
|
+
for name, header_value in value.items()
|
|
125
|
+
)
|
|
126
|
+
elif key == "additional_header_origins":
|
|
127
|
+
pairs.extend((key, origin) for origin in value)
|
|
128
|
+
else:
|
|
129
|
+
pairs.append((key, self._javascript_string(value)))
|
|
130
|
+
|
|
131
|
+
options = render_options or RenderImageOptions()
|
|
132
|
+
pairs.extend(self._render_option_pairs(options))
|
|
133
|
+
query = self._form_encode(pairs)
|
|
134
|
+
token = self._generate_hmac_token(query)
|
|
135
|
+
format_value = options.format or request.format
|
|
136
|
+
format_path = f"/{format_value}" if format_value is not None else ""
|
|
137
|
+
return (
|
|
138
|
+
f"{self._base_url}/v1/image/create-and-render/"
|
|
139
|
+
f"{self._api_id}/{token}{format_path}?{query}"
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
@staticmethod
|
|
143
|
+
def _javascript_string(value: Any) -> str:
|
|
144
|
+
if value is True:
|
|
145
|
+
return "true"
|
|
146
|
+
if value is False:
|
|
147
|
+
return "false"
|
|
148
|
+
if isinstance(value, float) and value.is_integer():
|
|
149
|
+
return str(int(value))
|
|
150
|
+
if isinstance(value, Sequence) and not isinstance(
|
|
151
|
+
value,
|
|
152
|
+
(str, bytes, bytearray),
|
|
153
|
+
):
|
|
154
|
+
return ",".join(UrlBuilder._javascript_string(item) for item in value)
|
|
155
|
+
return str(value)
|
|
156
|
+
|
|
157
|
+
@classmethod
|
|
158
|
+
def _form_encode(cls, pairs: Sequence[tuple[str, str]]) -> str:
|
|
159
|
+
return "&".join(
|
|
160
|
+
f"{cls._form_encode_component(key)}={cls._form_encode_component(value)}"
|
|
161
|
+
for key, value in pairs
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
@staticmethod
|
|
165
|
+
def _form_encode_component(value: str) -> str:
|
|
166
|
+
# Match WHATWG URLSearchParams rather than urllib's RFC 3986 defaults:
|
|
167
|
+
# spaces become '+', '*' remains literal, and '~' is percent-encoded.
|
|
168
|
+
return quote_plus(value, safe="*-._").replace("~", "%7E")
|
|
169
|
+
|
|
170
|
+
def _generate_hmac_token(self, query: str) -> str:
|
|
171
|
+
return hmac.new(
|
|
172
|
+
self._api_key.encode(),
|
|
173
|
+
query.encode(),
|
|
174
|
+
hashlib.sha256,
|
|
175
|
+
).hexdigest()
|
|
176
|
+
|
|
177
|
+
@classmethod
|
|
178
|
+
def _render_option_pairs(
|
|
179
|
+
cls,
|
|
180
|
+
options: RenderImageOptions,
|
|
181
|
+
*,
|
|
182
|
+
reserved_keys: set[str] | None = None,
|
|
183
|
+
) -> list[tuple[str, str]]:
|
|
184
|
+
reserved = reserved_keys or set()
|
|
185
|
+
|
|
186
|
+
def key(name: str) -> str:
|
|
187
|
+
return f"__ro_{name}" if name in reserved else name
|
|
188
|
+
|
|
189
|
+
pairs: list[tuple[str, str]] = []
|
|
190
|
+
if options.dpi is not None:
|
|
191
|
+
pairs.append((key("dpi"), str(options.dpi)))
|
|
192
|
+
if options.height is not None:
|
|
193
|
+
pairs.append((key("height"), str(options.height)))
|
|
194
|
+
if options.width is not None:
|
|
195
|
+
pairs.append((key("width"), str(options.width)))
|
|
196
|
+
if options.crop is not None:
|
|
197
|
+
pairs.extend(cls._crop_option_pairs(options.crop, reserved))
|
|
198
|
+
return pairs
|
|
199
|
+
|
|
200
|
+
@classmethod
|
|
201
|
+
def _crop_option_pairs(
|
|
202
|
+
cls,
|
|
203
|
+
crop: RenderImageCrop,
|
|
204
|
+
reserved: set[str],
|
|
205
|
+
) -> list[tuple[str, str]]:
|
|
206
|
+
def key(name: str) -> str:
|
|
207
|
+
return f"__ro_{name}" if name in reserved else name
|
|
208
|
+
|
|
209
|
+
pairs: list[tuple[str, str]] = []
|
|
210
|
+
if crop.aspect_ratio is not None:
|
|
211
|
+
pairs.append(
|
|
212
|
+
(
|
|
213
|
+
key("aspect_ratio"),
|
|
214
|
+
f"{crop.aspect_ratio.width}_{crop.aspect_ratio.height}",
|
|
215
|
+
)
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
x_origin = cls._crop_origin(crop.horizontal)
|
|
219
|
+
y_origin = cls._crop_origin(crop.vertical)
|
|
220
|
+
if crop.aspect_ratio_axis == "height":
|
|
221
|
+
x_origin = crop.computed_origin
|
|
222
|
+
elif crop.aspect_ratio_axis == "width":
|
|
223
|
+
y_origin = crop.computed_origin
|
|
224
|
+
if x_origin != "start":
|
|
225
|
+
pairs.append((key("x_origin"), x_origin))
|
|
226
|
+
if y_origin != "start":
|
|
227
|
+
pairs.append((key("y_origin"), y_origin))
|
|
228
|
+
|
|
229
|
+
cls._append_crop_span(pairs, crop.horizontal, "x", reserved)
|
|
230
|
+
cls._append_crop_span(pairs, crop.vertical, "y", reserved)
|
|
231
|
+
return pairs
|
|
232
|
+
|
|
233
|
+
@staticmethod
|
|
234
|
+
def _crop_origin(span: RenderImageCropSpan | None) -> str:
|
|
235
|
+
if span is not None and span.start is None and span.size is not None:
|
|
236
|
+
return span.origin
|
|
237
|
+
return "start"
|
|
238
|
+
|
|
239
|
+
@classmethod
|
|
240
|
+
def _append_crop_span(
|
|
241
|
+
cls,
|
|
242
|
+
pairs: list[tuple[str, str]],
|
|
243
|
+
span: RenderImageCropSpan | None,
|
|
244
|
+
axis: str,
|
|
245
|
+
reserved: set[str],
|
|
246
|
+
) -> None:
|
|
247
|
+
if span is None:
|
|
248
|
+
return
|
|
249
|
+
|
|
250
|
+
def key(name: str) -> str:
|
|
251
|
+
return f"__ro_{name}" if name in reserved else name
|
|
252
|
+
|
|
253
|
+
if span.start is not None:
|
|
254
|
+
pairs.append((key(f"{axis}_1"), f"{span.start.value}{span.start.unit}"))
|
|
255
|
+
if span.end is not None:
|
|
256
|
+
pairs.append((key(f"{axis}_2"), f"{span.end.value}{span.end.unit}"))
|
|
257
|
+
if span.size is not None:
|
|
258
|
+
long_name = "crop_width" if axis == "x" else "crop_height"
|
|
259
|
+
short_name = "crop_w" if axis == "x" else "crop_h"
|
|
260
|
+
value = f"{span.size.value}{span.size.unit}"
|
|
261
|
+
has_collision = False
|
|
262
|
+
if long_name in reserved:
|
|
263
|
+
pairs.append((f"__ro_{long_name}", value))
|
|
264
|
+
has_collision = True
|
|
265
|
+
if short_name in reserved:
|
|
266
|
+
pairs.append((f"__ro_{short_name}", value))
|
|
267
|
+
has_collision = True
|
|
268
|
+
if not has_collision:
|
|
269
|
+
pairs.append((long_name, value))
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""Synchronous client for the HTML/CSS to Image API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Mapping, Sequence
|
|
7
|
+
from typing import Any, TypeVar
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from ._request_mapper import RequestMapper
|
|
13
|
+
from ._response_mapper import ResponseMapper
|
|
14
|
+
from ._transport import HttpTransport
|
|
15
|
+
from ._url_builder import UrlBuilder
|
|
16
|
+
from .models import (
|
|
17
|
+
BatchCreateImageRequest,
|
|
18
|
+
CreateImageBatchResponse,
|
|
19
|
+
CreateImageBatchSuccessResponse,
|
|
20
|
+
CreateImageRequest,
|
|
21
|
+
CreateImageResponse,
|
|
22
|
+
CreateTemplatedImageRequest,
|
|
23
|
+
CreateUrlImageRequest,
|
|
24
|
+
DeleteImageResponse,
|
|
25
|
+
RenderImageOptions,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
_ClientT = TypeVar("_ClientT", bound="HtmlCssToImageClient")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class HtmlCssToImageClient:
|
|
32
|
+
"""Client for creating images with the HTML/CSS to Image API.
|
|
33
|
+
|
|
34
|
+
The client performs no automatic retries. To configure retry behavior,
|
|
35
|
+
proxies, certificates, connection limits, or custom transports, construct
|
|
36
|
+
an :class:`httpx.Client` and pass it through ``http_client``.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
api_id: HCTI API ID from the dashboard.
|
|
40
|
+
api_key: HCTI API key from the dashboard.
|
|
41
|
+
http_client: Optional configured HTTPX client. Injected clients remain
|
|
42
|
+
owned by the caller and are never closed by this object.
|
|
43
|
+
base_url: API origin. Override this primarily for testing or proxies.
|
|
44
|
+
|
|
45
|
+
Example:
|
|
46
|
+
>>> client = HtmlCssToImageClient("api-id", "api-key")
|
|
47
|
+
>>> request = CreateUrlImageRequest(url="https://example.com")
|
|
48
|
+
>>> result = client.create_image(request)
|
|
49
|
+
>>> if result.success:
|
|
50
|
+
... print(result.url)
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
api_id: str,
|
|
56
|
+
api_key: str,
|
|
57
|
+
*,
|
|
58
|
+
http_client: httpx.Client | None = None,
|
|
59
|
+
base_url: str = "https://hcti.io",
|
|
60
|
+
) -> None:
|
|
61
|
+
normalized_base_url = base_url.rstrip("/")
|
|
62
|
+
self._transport = HttpTransport(
|
|
63
|
+
api_id,
|
|
64
|
+
api_key,
|
|
65
|
+
http_client=http_client,
|
|
66
|
+
base_url=normalized_base_url,
|
|
67
|
+
)
|
|
68
|
+
self._url_builder = UrlBuilder(api_id, api_key, normalized_base_url)
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def from_env(
|
|
72
|
+
cls: type[_ClientT],
|
|
73
|
+
*,
|
|
74
|
+
http_client: httpx.Client | None = None,
|
|
75
|
+
base_url: str = "https://hcti.io",
|
|
76
|
+
) -> _ClientT:
|
|
77
|
+
"""Create a client from ``HCTI_API_ID`` and ``HCTI_API_KEY``.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
http_client: Optional caller-owned HTTPX client.
|
|
81
|
+
base_url: API origin. Override this primarily for testing.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
A configured :class:`HtmlCssToImageClient`.
|
|
85
|
+
|
|
86
|
+
Raises:
|
|
87
|
+
ValueError: If either required environment variable is missing.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
api_id = os.environ.get("HCTI_API_ID")
|
|
91
|
+
api_key = os.environ.get("HCTI_API_KEY")
|
|
92
|
+
if not api_id or not api_key:
|
|
93
|
+
raise ValueError(
|
|
94
|
+
"Missing environment variables HCTI_API_ID or HCTI_API_KEY"
|
|
95
|
+
)
|
|
96
|
+
return cls(
|
|
97
|
+
api_id,
|
|
98
|
+
api_key,
|
|
99
|
+
http_client=http_client,
|
|
100
|
+
base_url=base_url,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def create_image(self, request: CreateImageRequest) -> CreateImageResponse:
|
|
104
|
+
"""Create an image from HTML/CSS, a URL, or a saved template.
|
|
105
|
+
|
|
106
|
+
API validation and server errors are returned as
|
|
107
|
+
:class:`ApiErrorResponse`. HTTP transport failures and timeouts are
|
|
108
|
+
raised directly by HTTPX.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
request: Typed request describing the content to render.
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
A success response containing the image ID and URL, or an API
|
|
115
|
+
error response.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
TypeError: If ``request`` is not a supported request model.
|
|
119
|
+
UnexpectedResponseError: If a successful API response is malformed.
|
|
120
|
+
httpx.HTTPError: If the HTTP request cannot be completed.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
payload = RequestMapper.map_request(request, in_batch=False)
|
|
124
|
+
response = self._transport.post("/v1/image", payload)
|
|
125
|
+
return ResponseMapper.map_image_response(response)
|
|
126
|
+
|
|
127
|
+
def create_image_batch(
|
|
128
|
+
self,
|
|
129
|
+
variations: Sequence[BatchCreateImageRequest],
|
|
130
|
+
default_options: BatchCreateImageRequest | None = None,
|
|
131
|
+
) -> CreateImageBatchResponse:
|
|
132
|
+
"""Create several related images in one API call.
|
|
133
|
+
|
|
134
|
+
Empty ``html`` or ``url`` values are omitted in batch payloads so a
|
|
135
|
+
variation can inherit that value from ``default_options``. An empty
|
|
136
|
+
variation list returns a successful response without making an HTTP
|
|
137
|
+
request.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
variations: HTML/CSS or URL requests containing per-image values.
|
|
141
|
+
default_options: Optional values inherited by every variation.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
A batch success response, or an API error response.
|
|
145
|
+
|
|
146
|
+
Raises:
|
|
147
|
+
TypeError: If a template request or unsupported object is passed.
|
|
148
|
+
UnexpectedResponseError: If a successful API response is malformed.
|
|
149
|
+
httpx.HTTPError: If the HTTP request cannot be completed.
|
|
150
|
+
"""
|
|
151
|
+
|
|
152
|
+
if not variations:
|
|
153
|
+
return CreateImageBatchSuccessResponse(images=())
|
|
154
|
+
|
|
155
|
+
payload: dict[str, Any] = {
|
|
156
|
+
"variations": [
|
|
157
|
+
RequestMapper.map_batch_request(variation)
|
|
158
|
+
for variation in variations
|
|
159
|
+
],
|
|
160
|
+
}
|
|
161
|
+
if default_options is not None:
|
|
162
|
+
payload["default_options"] = RequestMapper.map_batch_request(
|
|
163
|
+
default_options
|
|
164
|
+
)
|
|
165
|
+
response = self._transport.post("/v1/image/batch", payload)
|
|
166
|
+
return ResponseMapper.map_batch_response(response)
|
|
167
|
+
|
|
168
|
+
def delete_image(self, image_id: str) -> DeleteImageResponse:
|
|
169
|
+
"""Delete one generated image.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
image_id: HCTI image identifier. It is safely encoded as one URL
|
|
173
|
+
path segment.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
A deletion success response, or a typed API error response.
|
|
177
|
+
|
|
178
|
+
Raises:
|
|
179
|
+
httpx.HTTPError: If the HTTP request cannot be completed.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
response = self._transport.delete(f"/v1/image/{quote(image_id, safe='')}")
|
|
183
|
+
return ResponseMapper.map_delete_response(response)
|
|
184
|
+
|
|
185
|
+
def delete_image_batch(
|
|
186
|
+
self,
|
|
187
|
+
image_ids: list[str] | tuple[str, ...],
|
|
188
|
+
) -> DeleteImageResponse:
|
|
189
|
+
"""Delete several generated images in one API call.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
image_ids: List or tuple of HCTI image identifiers to delete.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
A deletion success response, or a typed API error response.
|
|
196
|
+
|
|
197
|
+
Raises:
|
|
198
|
+
TypeError: If ``image_ids`` is not a list or tuple of strings.
|
|
199
|
+
httpx.HTTPError: If the HTTP request cannot be completed.
|
|
200
|
+
"""
|
|
201
|
+
|
|
202
|
+
if not isinstance(image_ids, (list, tuple)) or any(
|
|
203
|
+
not isinstance(image_id, str) for image_id in image_ids
|
|
204
|
+
):
|
|
205
|
+
raise TypeError("image_ids must be a list or tuple of strings")
|
|
206
|
+
response = self._transport.delete("/v1/image/batch", {"ids": list(image_ids)})
|
|
207
|
+
return ResponseMapper.map_delete_response(response)
|
|
208
|
+
|
|
209
|
+
def image_url(
|
|
210
|
+
self,
|
|
211
|
+
image_id: str,
|
|
212
|
+
render_options: RenderImageOptions | None = None,
|
|
213
|
+
) -> str:
|
|
214
|
+
"""Build a URL for retrieving an existing image.
|
|
215
|
+
|
|
216
|
+
Args:
|
|
217
|
+
image_id: HCTI image identifier.
|
|
218
|
+
render_options: Optional output format, resize, DPI, and crop
|
|
219
|
+
settings. Cropping is applied before resizing.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
The image URL. This method performs no HTTP request.
|
|
223
|
+
"""
|
|
224
|
+
|
|
225
|
+
return self._url_builder.image_url(image_id, render_options)
|
|
226
|
+
|
|
227
|
+
def generate_templated_image_url(
|
|
228
|
+
self,
|
|
229
|
+
request: CreateTemplatedImageRequest,
|
|
230
|
+
render_options: RenderImageOptions | None = None,
|
|
231
|
+
) -> str:
|
|
232
|
+
"""Generate a signed on-demand URL from a template request.
|
|
233
|
+
|
|
234
|
+
Args:
|
|
235
|
+
request: Complete saved-template request to sign.
|
|
236
|
+
render_options: Optional output format, resize, DPI, and crop
|
|
237
|
+
settings. Its format takes precedence over ``request.format``.
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
Signed HCTI image URL safe to expose to a frontend. This method
|
|
241
|
+
performs no HTTP request.
|
|
242
|
+
"""
|
|
243
|
+
|
|
244
|
+
return self._url_builder.templated_image_url(request, render_options)
|
|
245
|
+
|
|
246
|
+
def generate_templated_image_url_from_values(
|
|
247
|
+
self,
|
|
248
|
+
template_id: str,
|
|
249
|
+
template_values: Mapping[str, Any] | None = None,
|
|
250
|
+
template_version: int | None = None,
|
|
251
|
+
render_options: RenderImageOptions | None = None,
|
|
252
|
+
) -> str:
|
|
253
|
+
"""Generate a signed on-demand URL from separate template values.
|
|
254
|
+
|
|
255
|
+
Object and array template values are encoded as compact JSON before
|
|
256
|
+
the query string is signed.
|
|
257
|
+
|
|
258
|
+
Args:
|
|
259
|
+
template_id: Identifier of the saved template to render.
|
|
260
|
+
template_values: Values substituted into template variables.
|
|
261
|
+
template_version: Optional saved-template version.
|
|
262
|
+
render_options: Optional output format, resize, DPI, and crop
|
|
263
|
+
settings included in the signed URL.
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
Signed HCTI image URL safe to expose to a frontend. This method
|
|
267
|
+
performs no HTTP request.
|
|
268
|
+
"""
|
|
269
|
+
|
|
270
|
+
request = CreateTemplatedImageRequest(
|
|
271
|
+
template_id=template_id,
|
|
272
|
+
template_values={} if template_values is None else template_values,
|
|
273
|
+
template_version=template_version,
|
|
274
|
+
)
|
|
275
|
+
return self.generate_templated_image_url(request, render_options)
|
|
276
|
+
|
|
277
|
+
def generate_create_and_render_url(
|
|
278
|
+
self,
|
|
279
|
+
request: CreateUrlImageRequest,
|
|
280
|
+
render_options: RenderImageOptions | None = None,
|
|
281
|
+
) -> str:
|
|
282
|
+
"""Generate a signed URL that captures another URL on demand.
|
|
283
|
+
|
|
284
|
+
This method performs no HTTP request. PDF layout options are not
|
|
285
|
+
supported by the create-and-render endpoint and are omitted. Boolean
|
|
286
|
+
options set to ``False`` are also omitted to match the TypeScript
|
|
287
|
+
client.
|
|
288
|
+
|
|
289
|
+
Args:
|
|
290
|
+
request: URL screenshot request to sign.
|
|
291
|
+
render_options: Optional output format, resize, DPI, and crop
|
|
292
|
+
settings. Its format takes precedence over ``request.format``.
|
|
293
|
+
|
|
294
|
+
Returns:
|
|
295
|
+
Signed HCTI create-and-render URL safe to expose to a frontend.
|
|
296
|
+
"""
|
|
297
|
+
|
|
298
|
+
return self._url_builder.create_and_render_url(request, render_options)
|
|
299
|
+
|
|
300
|
+
def close(self) -> None:
|
|
301
|
+
"""Close the internally-created HTTPX client.
|
|
302
|
+
|
|
303
|
+
A client supplied through ``http_client`` is owned by the caller and
|
|
304
|
+
is intentionally left open.
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
self._transport.close()
|
|
308
|
+
|
|
309
|
+
def __enter__(self) -> HtmlCssToImageClient:
|
|
310
|
+
"""Return this client for use as a context manager."""
|
|
311
|
+
|
|
312
|
+
return self
|
|
313
|
+
|
|
314
|
+
def __exit__(self, *exc_info: object) -> None:
|
|
315
|
+
"""Close internally-owned HTTP resources on context exit."""
|
|
316
|
+
|
|
317
|
+
self.close()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Exceptions raised by the HTML/CSS to Image client."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class UnexpectedResponseError(Exception):
|
|
5
|
+
"""The API returned a successful response with an unexpected body.
|
|
6
|
+
|
|
7
|
+
This indicates that the client could not safely construct its documented
|
|
8
|
+
success model. API-declared errors are returned as ``ApiErrorResponse``;
|
|
9
|
+
HTTP transport failures continue to be raised by HTTPX.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
message: Description of the malformed response.
|
|
13
|
+
status_code: HTTP status code returned by the API.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
status_code: HTTP status code returned by the API.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, message: str, *, status_code: int) -> None:
|
|
20
|
+
super().__init__(message)
|
|
21
|
+
self.status_code = status_code
|