pdfconversionapi 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pdfconversionapi/__init__.py +80 -0
- pdfconversionapi/_async_client.py +290 -0
- pdfconversionapi/_base.py +134 -0
- pdfconversionapi/_client.py +315 -0
- pdfconversionapi/_core.py +593 -0
- pdfconversionapi/_exceptions.py +170 -0
- pdfconversionapi/_files.py +36 -0
- pdfconversionapi/_inputs.py +266 -0
- pdfconversionapi/_models.py +281 -0
- pdfconversionapi/_multipart.py +80 -0
- pdfconversionapi/_version.py +1 -0
- pdfconversionapi/py.typed +0 -0
- pdfconversionapi-0.1.0.dist-info/METADATA +410 -0
- pdfconversionapi-0.1.0.dist-info/RECORD +16 -0
- pdfconversionapi-0.1.0.dist-info/WHEEL +4 -0
- pdfconversionapi-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""The official Python client for the PDF Conversion API (https://pdfconversionapi.com).
|
|
2
|
+
|
|
3
|
+
>>> from pdfconversionapi import PdfConversionApi
|
|
4
|
+
>>> client = PdfConversionApi() # reads PDFCONVERSIONAPI_KEY
|
|
5
|
+
>>> result = client.convert_file("report.docx", "pdf")
|
|
6
|
+
>>> result.save_all("out") # writes out/report.pdf
|
|
7
|
+
|
|
8
|
+
Docs: https://pdfconversionapi.com/docs
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from ._async_client import AsyncPdfConversionApi
|
|
12
|
+
from ._client import PdfConversionApi
|
|
13
|
+
from ._core import DEFAULT_BASE_URL, ParamValue
|
|
14
|
+
from ._exceptions import (
|
|
15
|
+
APIConnectionError,
|
|
16
|
+
ApiError,
|
|
17
|
+
APITimeoutError,
|
|
18
|
+
AuthenticationError,
|
|
19
|
+
BadRequestError,
|
|
20
|
+
GatewayTimeoutError,
|
|
21
|
+
InternalServerError,
|
|
22
|
+
InvalidResponseError,
|
|
23
|
+
MissingApiKeyError,
|
|
24
|
+
NotFoundError,
|
|
25
|
+
PayloadTooLargeError,
|
|
26
|
+
PdfConversionApiError,
|
|
27
|
+
PermissionDeniedError,
|
|
28
|
+
RateLimitError,
|
|
29
|
+
ServiceUnavailableError,
|
|
30
|
+
StoredFileError,
|
|
31
|
+
UnprocessableEntityError,
|
|
32
|
+
)
|
|
33
|
+
from ._inputs import FileInput, SupportsRead, UploadFile
|
|
34
|
+
from ._models import (
|
|
35
|
+
AsyncConversionResult,
|
|
36
|
+
AsyncOutputFile,
|
|
37
|
+
Conversion,
|
|
38
|
+
ConversionResult,
|
|
39
|
+
OutputFile,
|
|
40
|
+
Usage,
|
|
41
|
+
)
|
|
42
|
+
from ._version import __version__
|
|
43
|
+
|
|
44
|
+
VERSION = __version__
|
|
45
|
+
"""The library's version, as on PyPI."""
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"DEFAULT_BASE_URL",
|
|
49
|
+
"VERSION",
|
|
50
|
+
"APIConnectionError",
|
|
51
|
+
"APITimeoutError",
|
|
52
|
+
"ApiError",
|
|
53
|
+
"AsyncConversionResult",
|
|
54
|
+
"AsyncOutputFile",
|
|
55
|
+
"AsyncPdfConversionApi",
|
|
56
|
+
"AuthenticationError",
|
|
57
|
+
"BadRequestError",
|
|
58
|
+
"Conversion",
|
|
59
|
+
"ConversionResult",
|
|
60
|
+
"FileInput",
|
|
61
|
+
"GatewayTimeoutError",
|
|
62
|
+
"InternalServerError",
|
|
63
|
+
"InvalidResponseError",
|
|
64
|
+
"MissingApiKeyError",
|
|
65
|
+
"NotFoundError",
|
|
66
|
+
"OutputFile",
|
|
67
|
+
"ParamValue",
|
|
68
|
+
"PayloadTooLargeError",
|
|
69
|
+
"PdfConversionApi",
|
|
70
|
+
"PdfConversionApiError",
|
|
71
|
+
"PermissionDeniedError",
|
|
72
|
+
"RateLimitError",
|
|
73
|
+
"ServiceUnavailableError",
|
|
74
|
+
"StoredFileError",
|
|
75
|
+
"SupportsRead",
|
|
76
|
+
"UnprocessableEntityError",
|
|
77
|
+
"UploadFile",
|
|
78
|
+
"Usage",
|
|
79
|
+
"__version__",
|
|
80
|
+
]
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""The asynchronous client: the same calls as PdfConversionApi, awaited."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from types import TracebackType
|
|
10
|
+
from typing import TypeVar
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from ._base import ClientBase
|
|
15
|
+
from ._core import (
|
|
16
|
+
DEFAULT_CONNECT_TIMEOUT,
|
|
17
|
+
DEFAULT_MAX_RETRIES,
|
|
18
|
+
DEFAULT_MAX_RETRY_WAIT,
|
|
19
|
+
DEFAULT_TIMEOUT,
|
|
20
|
+
Call,
|
|
21
|
+
Deadline,
|
|
22
|
+
ParamValue,
|
|
23
|
+
ParsedConversion,
|
|
24
|
+
RetryState,
|
|
25
|
+
api_error,
|
|
26
|
+
body_error,
|
|
27
|
+
httpx_timeout,
|
|
28
|
+
log_retry,
|
|
29
|
+
parse_conversion,
|
|
30
|
+
parse_conversions,
|
|
31
|
+
parse_usage,
|
|
32
|
+
request_headers,
|
|
33
|
+
request_id,
|
|
34
|
+
wait_after_send_error,
|
|
35
|
+
)
|
|
36
|
+
from ._files import discard_partial, safe_file_name, url_file_name
|
|
37
|
+
from ._inputs import FileInput
|
|
38
|
+
from ._models import AsyncConversionResult, AsyncOutputFile, Conversion, Usage
|
|
39
|
+
from ._multipart import MultipartBody
|
|
40
|
+
|
|
41
|
+
__all__ = ["AsyncPdfConversionApi"]
|
|
42
|
+
|
|
43
|
+
T = TypeVar("T")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def _default_sleep(seconds: float) -> None:
|
|
47
|
+
# anyio (an httpx dependency) sleeps under both asyncio and trio.
|
|
48
|
+
try:
|
|
49
|
+
import anyio
|
|
50
|
+
except ImportError: # pragma: no cover - httpx without anyio
|
|
51
|
+
await asyncio.sleep(seconds)
|
|
52
|
+
else:
|
|
53
|
+
await anyio.sleep(seconds)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class AsyncPdfConversionApi(ClientBase):
|
|
57
|
+
"""The PDF Conversion API client for asyncio (and trio): every call is awaited.
|
|
58
|
+
|
|
59
|
+
>>> async with AsyncPdfConversionApi() as client: # reads PDFCONVERSIONAPI_KEY
|
|
60
|
+
... result = await client.convert_file("report.docx", "pdf")
|
|
61
|
+
... await result.save_all("out")
|
|
62
|
+
|
|
63
|
+
The options are those of :class:`PdfConversionApi`, with an ``httpx.AsyncClient`` for
|
|
64
|
+
``http_client`` and an async ``sleep`` hook (for tests). Share one client between tasks.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
*,
|
|
70
|
+
api_key: str | None = None,
|
|
71
|
+
base_url: str | None = None,
|
|
72
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
73
|
+
connect_timeout: float = DEFAULT_CONNECT_TIMEOUT,
|
|
74
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
75
|
+
max_retry_wait: float = DEFAULT_MAX_RETRY_WAIT,
|
|
76
|
+
http_client: httpx.AsyncClient | None = None,
|
|
77
|
+
sleep: Callable[[float], Awaitable[None]] | None = None,
|
|
78
|
+
) -> None:
|
|
79
|
+
super().__init__(
|
|
80
|
+
api_key=api_key,
|
|
81
|
+
base_url=base_url,
|
|
82
|
+
timeout=timeout,
|
|
83
|
+
connect_timeout=connect_timeout,
|
|
84
|
+
max_retries=max_retries,
|
|
85
|
+
max_retry_wait=max_retry_wait,
|
|
86
|
+
)
|
|
87
|
+
if http_client is not None and not isinstance(http_client, httpx.AsyncClient):
|
|
88
|
+
raise TypeError(
|
|
89
|
+
f"http_client must be an httpx.AsyncClient, not {type(http_client).__name__}"
|
|
90
|
+
+ (" (use PdfConversionApi)" if isinstance(http_client, httpx.Client) else "")
|
|
91
|
+
)
|
|
92
|
+
self._owns_http = http_client is None
|
|
93
|
+
self._http = http_client if http_client is not None else httpx.AsyncClient()
|
|
94
|
+
self._sleep = sleep if sleep is not None else _default_sleep
|
|
95
|
+
|
|
96
|
+
async def aclose(self) -> None:
|
|
97
|
+
"""Closes the connections, unless the httpx.AsyncClient was passed in."""
|
|
98
|
+
if self._owns_http:
|
|
99
|
+
await self._http.aclose()
|
|
100
|
+
|
|
101
|
+
async def __aenter__(self) -> AsyncPdfConversionApi:
|
|
102
|
+
return self
|
|
103
|
+
|
|
104
|
+
async def __aexit__(
|
|
105
|
+
self,
|
|
106
|
+
exc_type: type[BaseException] | None,
|
|
107
|
+
exc: BaseException | None,
|
|
108
|
+
tb: TracebackType | None,
|
|
109
|
+
) -> None:
|
|
110
|
+
await self.aclose()
|
|
111
|
+
|
|
112
|
+
# The API
|
|
113
|
+
|
|
114
|
+
async def convert(
|
|
115
|
+
self,
|
|
116
|
+
from_format: str,
|
|
117
|
+
to_format: str,
|
|
118
|
+
files: FileInput | Sequence[FileInput] | None = None,
|
|
119
|
+
params: Mapping[str, ParamValue] | None = None,
|
|
120
|
+
*,
|
|
121
|
+
file_name: str | None = None,
|
|
122
|
+
store_file: bool = False,
|
|
123
|
+
timeout: float | None = None,
|
|
124
|
+
) -> AsyncConversionResult:
|
|
125
|
+
"""Converts files: ``POST /v2/convert/{from_format}/to/{to_format}``.
|
|
126
|
+
|
|
127
|
+
The arguments are those of :meth:`PdfConversionApi.convert`.
|
|
128
|
+
"""
|
|
129
|
+
call = self._convert_call(
|
|
130
|
+
from_format, to_format, files, params, file_name, store_file, timeout
|
|
131
|
+
)
|
|
132
|
+
return self._result(await self._json(call, parse_conversion))
|
|
133
|
+
|
|
134
|
+
async def convert_file(
|
|
135
|
+
self,
|
|
136
|
+
path: str | os.PathLike[str],
|
|
137
|
+
to_format: str,
|
|
138
|
+
params: Mapping[str, ParamValue] | None = None,
|
|
139
|
+
*,
|
|
140
|
+
file_name: str | None = None,
|
|
141
|
+
store_file: bool = False,
|
|
142
|
+
timeout: float | None = None,
|
|
143
|
+
) -> AsyncConversionResult:
|
|
144
|
+
"""Converts one file on disk; its extension is the input format."""
|
|
145
|
+
from_format, upload = self._file_input(path)
|
|
146
|
+
return await self.convert(
|
|
147
|
+
from_format,
|
|
148
|
+
to_format,
|
|
149
|
+
upload,
|
|
150
|
+
params,
|
|
151
|
+
file_name=file_name,
|
|
152
|
+
store_file=store_file,
|
|
153
|
+
timeout=timeout,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
async def usage(self, *, timeout: float | None = None) -> Usage:
|
|
157
|
+
"""Your plan, its limits and this month's count: ``GET /v2/usage``."""
|
|
158
|
+
return await self._json(self._usage_call(timeout), parse_usage)
|
|
159
|
+
|
|
160
|
+
async def conversions(self, *, timeout: float | None = None) -> list[Conversion]:
|
|
161
|
+
"""Every conversion the API offers: ``GET /v2/info``. Needs no key."""
|
|
162
|
+
return await self._json(self._conversions_call(timeout), parse_conversions)
|
|
163
|
+
|
|
164
|
+
async def download(self, url: str, *, timeout: float | None = None) -> bytes:
|
|
165
|
+
"""Downloads a stored file's ``url`` into memory. The key is not sent."""
|
|
166
|
+
call = self._download_call(url, timeout)
|
|
167
|
+
|
|
168
|
+
async def handle(response: httpx.Response, deadline: Deadline) -> bytes:
|
|
169
|
+
body = await self._read(response, call, deadline)
|
|
170
|
+
if response.status_code != 200:
|
|
171
|
+
raise api_error(response.status_code, response.headers, body)
|
|
172
|
+
return bytes(body)
|
|
173
|
+
|
|
174
|
+
return await self._execute(call, handle)
|
|
175
|
+
|
|
176
|
+
async def download_to(
|
|
177
|
+
self, url: str, path: str | os.PathLike[str], *, timeout: float | None = None
|
|
178
|
+
) -> Path:
|
|
179
|
+
"""Downloads a stored file's ``url`` to ``path``, streamed to disk, and returns the path.
|
|
180
|
+
|
|
181
|
+
If ``path`` is an existing folder, the file is written inside it under the name at the
|
|
182
|
+
end of the URL. An existing file is overwritten. The key is not sent.
|
|
183
|
+
"""
|
|
184
|
+
call = self._download_call(url, timeout)
|
|
185
|
+
target = Path(path)
|
|
186
|
+
if target.is_dir():
|
|
187
|
+
target = target / safe_file_name(url_file_name(call.url))
|
|
188
|
+
|
|
189
|
+
async def handle(response: httpx.Response, deadline: Deadline) -> Path:
|
|
190
|
+
if response.status_code != 200:
|
|
191
|
+
body = await self._read(response, call, deadline)
|
|
192
|
+
raise api_error(response.status_code, response.headers, body)
|
|
193
|
+
try:
|
|
194
|
+
with open(target, "wb") as out:
|
|
195
|
+
async for chunk in response.aiter_bytes():
|
|
196
|
+
out.write(chunk)
|
|
197
|
+
deadline.check()
|
|
198
|
+
except httpx.HTTPError as exc:
|
|
199
|
+
discard_partial(target)
|
|
200
|
+
raise body_error(exc, call, self._settings) from exc
|
|
201
|
+
except BaseException:
|
|
202
|
+
discard_partial(target)
|
|
203
|
+
raise
|
|
204
|
+
return target
|
|
205
|
+
|
|
206
|
+
return await self._execute(call, handle)
|
|
207
|
+
|
|
208
|
+
async def delete_stored_file(self, file_id: str, *, timeout: float | None = None) -> bool:
|
|
209
|
+
"""Deletes a stored file now: ``DELETE /v2/d/{file_id}``.
|
|
210
|
+
|
|
211
|
+
Returns True when it was deleted, False when there was nothing to delete.
|
|
212
|
+
"""
|
|
213
|
+
call = self._delete_call(file_id, timeout)
|
|
214
|
+
|
|
215
|
+
async def handle(response: httpx.Response, deadline: Deadline) -> bool:
|
|
216
|
+
if 200 <= response.status_code < 300:
|
|
217
|
+
return True
|
|
218
|
+
body = await self._read(response, call, deadline)
|
|
219
|
+
if response.status_code == 404:
|
|
220
|
+
return False
|
|
221
|
+
raise api_error(response.status_code, response.headers, body)
|
|
222
|
+
|
|
223
|
+
return await self._execute(call, handle)
|
|
224
|
+
|
|
225
|
+
# Plumbing
|
|
226
|
+
|
|
227
|
+
def _result(self, parsed: ParsedConversion) -> AsyncConversionResult:
|
|
228
|
+
files = [AsyncOutputFile(entry, self) for entry in parsed.files]
|
|
229
|
+
return AsyncConversionResult(
|
|
230
|
+
files, parsed.conversion_cost, parsed.conversion_time, parsed.request_id
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
async def _json(self, call: Call, parse: Callable[[bytearray, str | None], T]) -> T:
|
|
234
|
+
async def handle(response: httpx.Response, deadline: Deadline) -> T:
|
|
235
|
+
body = await self._read(response, call, deadline)
|
|
236
|
+
if response.status_code != 200:
|
|
237
|
+
raise api_error(response.status_code, response.headers, body)
|
|
238
|
+
return parse(body, request_id(response.headers))
|
|
239
|
+
|
|
240
|
+
return await self._execute(call, handle)
|
|
241
|
+
|
|
242
|
+
async def _read(self, response: httpx.Response, call: Call, deadline: Deadline) -> bytearray:
|
|
243
|
+
body = bytearray()
|
|
244
|
+
try:
|
|
245
|
+
async for chunk in response.aiter_bytes():
|
|
246
|
+
body += chunk
|
|
247
|
+
deadline.check()
|
|
248
|
+
except httpx.HTTPError as exc:
|
|
249
|
+
raise body_error(exc, call, self._settings) from exc
|
|
250
|
+
return body
|
|
251
|
+
|
|
252
|
+
def _build(self, call: Call, deadline: Deadline) -> httpx.Request:
|
|
253
|
+
body = MultipartBody(call.fields) if call.fields is not None else None
|
|
254
|
+
request = self._http.build_request(
|
|
255
|
+
call.method,
|
|
256
|
+
call.url,
|
|
257
|
+
headers=request_headers(call, self._settings, body),
|
|
258
|
+
content=body.achunks(deadline.check) if body is not None else None,
|
|
259
|
+
timeout=httpx_timeout(call, self._settings),
|
|
260
|
+
)
|
|
261
|
+
if not call.authorized:
|
|
262
|
+
request.headers.pop("Authorization", None)
|
|
263
|
+
return request
|
|
264
|
+
|
|
265
|
+
async def _execute(
|
|
266
|
+
self, call: Call, handle: Callable[[httpx.Response, Deadline], Awaitable[T]]
|
|
267
|
+
) -> T:
|
|
268
|
+
"""Sends ``call`` with the retry rules, then hands the final response to ``handle``."""
|
|
269
|
+
state = RetryState(self._settings.max_retries, self._settings.max_retry_wait)
|
|
270
|
+
while True:
|
|
271
|
+
state.next_attempt()
|
|
272
|
+
deadline = Deadline(call)
|
|
273
|
+
request = self._build(call, deadline)
|
|
274
|
+
try:
|
|
275
|
+
response = await self._http.send(request, stream=True, follow_redirects=False)
|
|
276
|
+
except httpx.TransportError as exc:
|
|
277
|
+
wait = wait_after_send_error(exc, state, call, self._settings)
|
|
278
|
+
why = f"no response ({type(exc).__name__})"
|
|
279
|
+
else:
|
|
280
|
+
try:
|
|
281
|
+
retry = state.after_status(
|
|
282
|
+
response.status_code, response.headers.get("retry-after")
|
|
283
|
+
)
|
|
284
|
+
if retry is None:
|
|
285
|
+
return await handle(response, deadline)
|
|
286
|
+
wait, why = retry, f"HTTP {response.status_code}"
|
|
287
|
+
finally:
|
|
288
|
+
await response.aclose()
|
|
289
|
+
log_retry(call, state, wait, why)
|
|
290
|
+
await self._sleep(wait)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""The part of the client that the sync and async versions share: settings and the calls."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
|
|
8
|
+
from ._core import (
|
|
9
|
+
DEFAULT_CONNECT_TIMEOUT,
|
|
10
|
+
DEFAULT_MAX_RETRIES,
|
|
11
|
+
DEFAULT_MAX_RETRY_WAIT,
|
|
12
|
+
DEFAULT_TIMEOUT,
|
|
13
|
+
Call,
|
|
14
|
+
ParamValue,
|
|
15
|
+
Settings,
|
|
16
|
+
call_timeout,
|
|
17
|
+
check_file_id,
|
|
18
|
+
check_format,
|
|
19
|
+
check_url,
|
|
20
|
+
convert_fields,
|
|
21
|
+
require_key,
|
|
22
|
+
resolve_settings,
|
|
23
|
+
)
|
|
24
|
+
from ._inputs import UploadFile, path_extension
|
|
25
|
+
|
|
26
|
+
__all__ = ["ClientBase"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ClientBase:
|
|
30
|
+
"""Settings and request building; holds no per-request state, so it is safe to share."""
|
|
31
|
+
|
|
32
|
+
_settings: Settings
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
api_key: str | None = None,
|
|
38
|
+
base_url: str | None = None,
|
|
39
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
40
|
+
connect_timeout: float = DEFAULT_CONNECT_TIMEOUT,
|
|
41
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
42
|
+
max_retry_wait: float = DEFAULT_MAX_RETRY_WAIT,
|
|
43
|
+
) -> None:
|
|
44
|
+
self._settings = resolve_settings(
|
|
45
|
+
api_key=api_key,
|
|
46
|
+
base_url=base_url,
|
|
47
|
+
timeout=timeout,
|
|
48
|
+
connect_timeout=connect_timeout,
|
|
49
|
+
max_retries=max_retries,
|
|
50
|
+
max_retry_wait=max_retry_wait,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def base_url(self) -> str:
|
|
55
|
+
"""The API's address, without a trailing slash."""
|
|
56
|
+
return self._settings.base_url
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def timeout(self) -> float:
|
|
60
|
+
"""Seconds each attempt may take, for the whole response."""
|
|
61
|
+
return self._settings.timeout
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def connect_timeout(self) -> float:
|
|
65
|
+
"""Seconds to wait for a connection to open."""
|
|
66
|
+
return self._settings.connect_timeout
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def max_retries(self) -> int:
|
|
70
|
+
"""Retries after the first attempt (section "Errors and retries" of the README)."""
|
|
71
|
+
return self._settings.max_retries
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def max_retry_wait(self) -> float:
|
|
75
|
+
"""The longest ``Retry-After`` that is waited for; a longer one is raised at once."""
|
|
76
|
+
return self._settings.max_retry_wait
|
|
77
|
+
|
|
78
|
+
def __repr__(self) -> str:
|
|
79
|
+
key = "set" if self._settings.api_key else "missing"
|
|
80
|
+
return f"{type(self).__name__}(base_url={self.base_url!r}, api_key=<{key}>)"
|
|
81
|
+
|
|
82
|
+
# Calls. Each validates its arguments and raises before anything is sent.
|
|
83
|
+
|
|
84
|
+
def _convert_call(
|
|
85
|
+
self,
|
|
86
|
+
from_format: str,
|
|
87
|
+
to_format: str,
|
|
88
|
+
files: object,
|
|
89
|
+
params: Mapping[str, ParamValue] | None,
|
|
90
|
+
file_name: str | None,
|
|
91
|
+
store_file: bool,
|
|
92
|
+
timeout: float | None,
|
|
93
|
+
) -> Call:
|
|
94
|
+
source = check_format(from_format, "from_format")
|
|
95
|
+
target = check_format(to_format, "to_format")
|
|
96
|
+
fields = convert_fields(files, params, file_name, store_file)
|
|
97
|
+
seconds = call_timeout(self._settings, timeout)
|
|
98
|
+
require_key(self._settings)
|
|
99
|
+
return Call(
|
|
100
|
+
"POST",
|
|
101
|
+
f"{self._settings.base_url}/v2/convert/{source}/to/{target}",
|
|
102
|
+
seconds,
|
|
103
|
+
authorized=True,
|
|
104
|
+
fields=fields,
|
|
105
|
+
conversion=True,
|
|
106
|
+
label=f"{source}/to/{target}",
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def _file_input(path: str | os.PathLike[str]) -> tuple[str, UploadFile]:
|
|
111
|
+
return path_extension(path), UploadFile.from_path(path)
|
|
112
|
+
|
|
113
|
+
def _usage_call(self, timeout: float | None) -> Call:
|
|
114
|
+
seconds = call_timeout(self._settings, timeout)
|
|
115
|
+
require_key(self._settings)
|
|
116
|
+
url = f"{self._settings.base_url}/v2/usage"
|
|
117
|
+
return Call("GET", url, seconds, authorized=True, label="usage")
|
|
118
|
+
|
|
119
|
+
def _conversions_call(self, timeout: float | None) -> Call:
|
|
120
|
+
seconds = call_timeout(self._settings, timeout)
|
|
121
|
+
url = f"{self._settings.base_url}/v2/info"
|
|
122
|
+
return Call("GET", url, seconds, label="conversions")
|
|
123
|
+
|
|
124
|
+
def _download_call(self, url: str, timeout: float | None) -> Call:
|
|
125
|
+
checked = check_url(url)
|
|
126
|
+
seconds = call_timeout(self._settings, timeout)
|
|
127
|
+
return Call("GET", checked, seconds, accept_json=False, label="download")
|
|
128
|
+
|
|
129
|
+
def _delete_call(self, file_id: str, timeout: float | None) -> Call:
|
|
130
|
+
checked = check_file_id(file_id)
|
|
131
|
+
seconds = call_timeout(self._settings, timeout)
|
|
132
|
+
require_key(self._settings)
|
|
133
|
+
url = f"{self._settings.base_url}/v2/d/{checked}"
|
|
134
|
+
return Call("DELETE", url, seconds, authorized=True, label="delete_stored_file")
|