podpislon-sdk 1.0.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.
- podpislon/__init__.py +106 -0
- podpislon/_transport.py +280 -0
- podpislon/_utils.py +142 -0
- podpislon/_version.py +24 -0
- podpislon/client.py +145 -0
- podpislon/enums.py +46 -0
- podpislon/exceptions.py +169 -0
- podpislon/models/__init__.py +36 -0
- podpislon/models/common.py +58 -0
- podpislon/models/company.py +36 -0
- podpislon/models/contact.py +33 -0
- podpislon/models/document.py +116 -0
- podpislon/models/payment.py +30 -0
- podpislon/models/webhook.py +59 -0
- podpislon/py.typed +0 -0
- podpislon/resources/__init__.py +7 -0
- podpislon/resources/_base.py +49 -0
- podpislon/resources/company.py +27 -0
- podpislon/resources/documents.py +362 -0
- podpislon/resources/payments.py +19 -0
- podpislon/webhooks/__init__.py +6 -0
- podpislon/webhooks/handler.py +204 -0
- podpislon/webhooks/parser.py +79 -0
- podpislon_sdk-1.0.0.dist-info/METADATA +729 -0
- podpislon_sdk-1.0.0.dist-info/RECORD +27 -0
- podpislon_sdk-1.0.0.dist-info/WHEEL +4 -0
- podpislon_sdk-1.0.0.dist-info/licenses/LICENSE +32 -0
podpislon/__init__.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""podpislon-sdk — unofficial async Python SDK for the Podpislon API.
|
|
2
|
+
|
|
3
|
+
This SDK is **not affiliated** with, endorsed by, or in any way officially
|
|
4
|
+
connected with the company that operates https://podpislon.ru.
|
|
5
|
+
|
|
6
|
+
Quick start
|
|
7
|
+
-----------
|
|
8
|
+
.. code-block:: python
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
from podpislon import PodpislonClient
|
|
12
|
+
|
|
13
|
+
async def main():
|
|
14
|
+
async with PodpislonClient(api_key="...") as client:
|
|
15
|
+
info = await client.company.get_info()
|
|
16
|
+
print("Signings left:", info.signings_left)
|
|
17
|
+
|
|
18
|
+
asyncio.run(main())
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from podpislon.client import PodpislonClient
|
|
24
|
+
from podpislon.enums import DocumentStatus, WebhookEventType
|
|
25
|
+
from podpislon.exceptions import (
|
|
26
|
+
PodpislonAPIError,
|
|
27
|
+
PodpislonAuthenticationError,
|
|
28
|
+
PodpislonConfigurationError,
|
|
29
|
+
PodpislonError,
|
|
30
|
+
PodpislonNotFoundError,
|
|
31
|
+
PodpislonPermissionError,
|
|
32
|
+
PodpislonRateLimitError,
|
|
33
|
+
PodpislonServerError,
|
|
34
|
+
PodpislonTransportError,
|
|
35
|
+
PodpislonUnknownEventError,
|
|
36
|
+
PodpislonValidationError,
|
|
37
|
+
PodpislonWebhookError,
|
|
38
|
+
PodpislonWebhookSignatureError,
|
|
39
|
+
)
|
|
40
|
+
from podpislon.models import (
|
|
41
|
+
AddDocumentResult,
|
|
42
|
+
APIResponse,
|
|
43
|
+
ClientDataRequestSubmittedEvent,
|
|
44
|
+
Company,
|
|
45
|
+
CompanyInfo,
|
|
46
|
+
Contact,
|
|
47
|
+
Document,
|
|
48
|
+
DocumentOpenedEvent,
|
|
49
|
+
DocumentSignedEvent,
|
|
50
|
+
Filter,
|
|
51
|
+
PaginatedDocuments,
|
|
52
|
+
PaginationMeta,
|
|
53
|
+
Payment,
|
|
54
|
+
PaymentSystem,
|
|
55
|
+
WebhookEvent,
|
|
56
|
+
)
|
|
57
|
+
from podpislon.webhooks import WebhookHandler, WebhookSignatureVerifier, parse_event
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
from podpislon._version import __version__ # type: ignore[import-not-found]
|
|
61
|
+
except ImportError: # pragma: no cover - source checkout without build step
|
|
62
|
+
__version__ = "0.0.0+unknown"
|
|
63
|
+
|
|
64
|
+
__all__ = [
|
|
65
|
+
# Client
|
|
66
|
+
"PodpislonClient",
|
|
67
|
+
# Enums
|
|
68
|
+
"DocumentStatus",
|
|
69
|
+
"WebhookEventType",
|
|
70
|
+
# Models
|
|
71
|
+
"APIResponse",
|
|
72
|
+
"AddDocumentResult",
|
|
73
|
+
"ClientDataRequestSubmittedEvent",
|
|
74
|
+
"Company",
|
|
75
|
+
"CompanyInfo",
|
|
76
|
+
"Contact",
|
|
77
|
+
"Document",
|
|
78
|
+
"DocumentOpenedEvent",
|
|
79
|
+
"DocumentSignedEvent",
|
|
80
|
+
"Filter",
|
|
81
|
+
"PaginatedDocuments",
|
|
82
|
+
"PaginationMeta",
|
|
83
|
+
"Payment",
|
|
84
|
+
"PaymentSystem",
|
|
85
|
+
"WebhookEvent",
|
|
86
|
+
# Webhooks
|
|
87
|
+
"WebhookHandler",
|
|
88
|
+
"WebhookSignatureVerifier",
|
|
89
|
+
"parse_event",
|
|
90
|
+
# Exceptions
|
|
91
|
+
"PodpislonAPIError",
|
|
92
|
+
"PodpislonAuthenticationError",
|
|
93
|
+
"PodpislonConfigurationError",
|
|
94
|
+
"PodpislonError",
|
|
95
|
+
"PodpislonNotFoundError",
|
|
96
|
+
"PodpislonPermissionError",
|
|
97
|
+
"PodpislonRateLimitError",
|
|
98
|
+
"PodpislonServerError",
|
|
99
|
+
"PodpislonTransportError",
|
|
100
|
+
"PodpislonUnknownEventError",
|
|
101
|
+
"PodpislonValidationError",
|
|
102
|
+
"PodpislonWebhookError",
|
|
103
|
+
"PodpislonWebhookSignatureError",
|
|
104
|
+
# Version
|
|
105
|
+
"__version__",
|
|
106
|
+
]
|
podpislon/_transport.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Low-level async HTTP transport used by the resource layer.
|
|
2
|
+
|
|
3
|
+
Splits the HTTP plumbing (rate limiting, retries, error mapping, JSON
|
|
4
|
+
parsing) away from the resource methods so that each resource stays
|
|
5
|
+
focused on the business contract.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import logging
|
|
12
|
+
import random
|
|
13
|
+
from typing import Any, Mapping, Sequence
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from podpislon._utils import AsyncRateLimiter
|
|
18
|
+
from podpislon.exceptions import (
|
|
19
|
+
PodpislonAPIError,
|
|
20
|
+
PodpislonRateLimitError,
|
|
21
|
+
PodpislonServerError,
|
|
22
|
+
PodpislonTransportError,
|
|
23
|
+
raise_for_status,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_LOGGER = logging.getLogger("podpislon")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RetryPolicy:
|
|
30
|
+
"""Exponential-backoff retry policy for transient failures."""
|
|
31
|
+
|
|
32
|
+
__slots__ = ("max_retries", "backoff_factor", "max_backoff", "retry_on_statuses")
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
max_retries: int = 3,
|
|
38
|
+
backoff_factor: float = 0.5,
|
|
39
|
+
max_backoff: float = 30.0,
|
|
40
|
+
retry_on_statuses: Sequence[int] = (429, 500, 502, 503, 504),
|
|
41
|
+
) -> None:
|
|
42
|
+
if max_retries < 0:
|
|
43
|
+
raise ValueError("max_retries must be >= 0")
|
|
44
|
+
if backoff_factor < 0:
|
|
45
|
+
raise ValueError("backoff_factor must be >= 0")
|
|
46
|
+
if max_backoff < 0:
|
|
47
|
+
raise ValueError("max_backoff must be >= 0")
|
|
48
|
+
self.max_retries = max_retries
|
|
49
|
+
self.backoff_factor = backoff_factor
|
|
50
|
+
self.max_backoff = max_backoff
|
|
51
|
+
self.retry_on_statuses = tuple(retry_on_statuses)
|
|
52
|
+
|
|
53
|
+
def compute_delay(self, attempt: int, retry_after: float | None = None) -> float:
|
|
54
|
+
"""Wait at least ``retry_after`` seconds, otherwise back off exponentially.
|
|
55
|
+
|
|
56
|
+
A small random jitter (±25%) prevents the well-known thundering-herd
|
|
57
|
+
when many parallel coroutines all retry at the same moment.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
if retry_after is not None and retry_after > 0:
|
|
61
|
+
return min(retry_after, self.max_backoff)
|
|
62
|
+
base = self.backoff_factor * (2**attempt)
|
|
63
|
+
jitter = random.uniform(0.75, 1.25)
|
|
64
|
+
return min(base * jitter, self.max_backoff)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Transport:
|
|
68
|
+
"""Thin wrapper around :class:`httpx.AsyncClient`.
|
|
69
|
+
|
|
70
|
+
Responsibilities:
|
|
71
|
+
|
|
72
|
+
* inject the ``X-Api-Key`` header on every request;
|
|
73
|
+
* apply the global rate limiter (4 RPS);
|
|
74
|
+
* retry transient failures (``429`` and ``5xx``);
|
|
75
|
+
* convert HTTP failures to typed exceptions;
|
|
76
|
+
* decode the JSON response body.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self,
|
|
81
|
+
*,
|
|
82
|
+
api_key: str,
|
|
83
|
+
base_url: str,
|
|
84
|
+
timeout: float | httpx.Timeout,
|
|
85
|
+
retry_policy: RetryPolicy,
|
|
86
|
+
rate_limiter: AsyncRateLimiter | None,
|
|
87
|
+
user_agent: str,
|
|
88
|
+
client: httpx.AsyncClient | None = None,
|
|
89
|
+
) -> None:
|
|
90
|
+
self._api_key = api_key
|
|
91
|
+
self._base_url = base_url.rstrip("/")
|
|
92
|
+
self._retry_policy = retry_policy
|
|
93
|
+
self._rate_limiter = rate_limiter
|
|
94
|
+
self._user_agent = user_agent
|
|
95
|
+
self._owns_client = client is None
|
|
96
|
+
self._client: httpx.AsyncClient = client or httpx.AsyncClient(
|
|
97
|
+
base_url=self._base_url,
|
|
98
|
+
timeout=timeout,
|
|
99
|
+
headers=self._default_headers(),
|
|
100
|
+
follow_redirects=True,
|
|
101
|
+
)
|
|
102
|
+
if not self._owns_client:
|
|
103
|
+
# Make sure caller-supplied clients still send our headers.
|
|
104
|
+
for key, value in self._default_headers().items():
|
|
105
|
+
self._client.headers.setdefault(key, value)
|
|
106
|
+
|
|
107
|
+
def _default_headers(self) -> dict[str, str]:
|
|
108
|
+
return {
|
|
109
|
+
"X-Api-Key": self._api_key,
|
|
110
|
+
"Accept": "application/json",
|
|
111
|
+
"User-Agent": self._user_agent,
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def base_url(self) -> str:
|
|
116
|
+
return self._base_url
|
|
117
|
+
|
|
118
|
+
async def aclose(self) -> None:
|
|
119
|
+
if self._owns_client:
|
|
120
|
+
await self._client.aclose()
|
|
121
|
+
|
|
122
|
+
async def request(
|
|
123
|
+
self,
|
|
124
|
+
method: str,
|
|
125
|
+
path: str,
|
|
126
|
+
*,
|
|
127
|
+
json: Any = None,
|
|
128
|
+
data: Mapping[str, Any] | None = None,
|
|
129
|
+
files: Mapping[str, Any] | Sequence[tuple[str, Any]] | None = None,
|
|
130
|
+
params: Mapping[str, Any] | None = None,
|
|
131
|
+
headers: Mapping[str, str] | None = None,
|
|
132
|
+
) -> "Response":
|
|
133
|
+
"""Issue an HTTP request and return the parsed response."""
|
|
134
|
+
|
|
135
|
+
url = path if path.startswith(("http://", "https://")) else path
|
|
136
|
+
attempt = 0
|
|
137
|
+
last_exc: Exception | None = None
|
|
138
|
+
|
|
139
|
+
while True:
|
|
140
|
+
try:
|
|
141
|
+
if self._rate_limiter is not None:
|
|
142
|
+
async with self._rate_limiter.slot():
|
|
143
|
+
http_response = await self._client.request(
|
|
144
|
+
method,
|
|
145
|
+
url,
|
|
146
|
+
json=json,
|
|
147
|
+
data=data,
|
|
148
|
+
files=files,
|
|
149
|
+
params=params,
|
|
150
|
+
headers=headers,
|
|
151
|
+
)
|
|
152
|
+
else:
|
|
153
|
+
http_response = await self._client.request(
|
|
154
|
+
method,
|
|
155
|
+
url,
|
|
156
|
+
json=json,
|
|
157
|
+
data=data,
|
|
158
|
+
files=files,
|
|
159
|
+
params=params,
|
|
160
|
+
headers=headers,
|
|
161
|
+
)
|
|
162
|
+
except httpx.TimeoutException as exc:
|
|
163
|
+
last_exc = exc
|
|
164
|
+
_LOGGER.debug("Timeout on %s %s (attempt %d)", method, url, attempt)
|
|
165
|
+
if attempt >= self._retry_policy.max_retries:
|
|
166
|
+
raise PodpislonTransportError(f"Request timed out: {exc}") from exc
|
|
167
|
+
await asyncio.sleep(self._retry_policy.compute_delay(attempt))
|
|
168
|
+
attempt += 1
|
|
169
|
+
continue
|
|
170
|
+
except httpx.TransportError as exc:
|
|
171
|
+
last_exc = exc
|
|
172
|
+
_LOGGER.debug(
|
|
173
|
+
"Transport error on %s %s (attempt %d): %s", method, url, attempt, exc
|
|
174
|
+
)
|
|
175
|
+
if attempt >= self._retry_policy.max_retries:
|
|
176
|
+
raise PodpislonTransportError(str(exc)) from exc
|
|
177
|
+
await asyncio.sleep(self._retry_policy.compute_delay(attempt))
|
|
178
|
+
attempt += 1
|
|
179
|
+
continue
|
|
180
|
+
|
|
181
|
+
status = http_response.status_code
|
|
182
|
+
|
|
183
|
+
if (
|
|
184
|
+
status in self._retry_policy.retry_on_statuses
|
|
185
|
+
and attempt < self._retry_policy.max_retries
|
|
186
|
+
):
|
|
187
|
+
retry_after = _parse_retry_after(http_response.headers)
|
|
188
|
+
delay = self._retry_policy.compute_delay(attempt, retry_after)
|
|
189
|
+
_LOGGER.debug(
|
|
190
|
+
"Retrying %s %s after %.2fs (status=%s, attempt=%d)",
|
|
191
|
+
method,
|
|
192
|
+
url,
|
|
193
|
+
delay,
|
|
194
|
+
status,
|
|
195
|
+
attempt,
|
|
196
|
+
)
|
|
197
|
+
await asyncio.sleep(delay)
|
|
198
|
+
attempt += 1
|
|
199
|
+
continue
|
|
200
|
+
|
|
201
|
+
response = Response.from_httpx(http_response)
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
raise_for_status(
|
|
205
|
+
status_code=status,
|
|
206
|
+
response_body=response.json_body if response.is_json else response.text,
|
|
207
|
+
request_id=response.request_id,
|
|
208
|
+
headers=http_response.headers,
|
|
209
|
+
)
|
|
210
|
+
except (PodpislonRateLimitError, PodpislonServerError):
|
|
211
|
+
raise
|
|
212
|
+
except PodpislonAPIError:
|
|
213
|
+
raise
|
|
214
|
+
|
|
215
|
+
return response
|
|
216
|
+
|
|
217
|
+
# Unreachable, but mypy/typing wants an explicit raise.
|
|
218
|
+
if last_exc is not None: # pragma: no cover
|
|
219
|
+
raise PodpislonTransportError(str(last_exc)) from last_exc
|
|
220
|
+
raise PodpislonTransportError("Unknown transport error") # pragma: no cover
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class Response:
|
|
224
|
+
"""Lightweight wrapper that exposes JSON / headers / status without httpx leaking out."""
|
|
225
|
+
|
|
226
|
+
__slots__ = ("status_code", "headers", "text", "_json_body", "_is_json", "request_id")
|
|
227
|
+
|
|
228
|
+
def __init__(
|
|
229
|
+
self,
|
|
230
|
+
*,
|
|
231
|
+
status_code: int,
|
|
232
|
+
headers: Mapping[str, str],
|
|
233
|
+
text: str,
|
|
234
|
+
json_body: Any,
|
|
235
|
+
is_json: bool,
|
|
236
|
+
request_id: str | None,
|
|
237
|
+
) -> None:
|
|
238
|
+
self.status_code = status_code
|
|
239
|
+
self.headers = headers
|
|
240
|
+
self.text = text
|
|
241
|
+
self._json_body = json_body
|
|
242
|
+
self._is_json = is_json
|
|
243
|
+
self.request_id = request_id
|
|
244
|
+
|
|
245
|
+
@property
|
|
246
|
+
def json_body(self) -> Any:
|
|
247
|
+
return self._json_body
|
|
248
|
+
|
|
249
|
+
@property
|
|
250
|
+
def is_json(self) -> bool:
|
|
251
|
+
return self._is_json
|
|
252
|
+
|
|
253
|
+
@classmethod
|
|
254
|
+
def from_httpx(cls, response: httpx.Response) -> "Response":
|
|
255
|
+
content_type = response.headers.get("content-type", "")
|
|
256
|
+
is_json = "application/json" in content_type.lower()
|
|
257
|
+
json_body: Any = None
|
|
258
|
+
if is_json and response.content:
|
|
259
|
+
try:
|
|
260
|
+
json_body = response.json()
|
|
261
|
+
except ValueError:
|
|
262
|
+
is_json = False
|
|
263
|
+
return cls(
|
|
264
|
+
status_code=response.status_code,
|
|
265
|
+
headers=dict(response.headers),
|
|
266
|
+
text=response.text,
|
|
267
|
+
json_body=json_body,
|
|
268
|
+
is_json=is_json,
|
|
269
|
+
request_id=response.headers.get("x-request-id"),
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _parse_retry_after(headers: Mapping[str, str]) -> float | None:
|
|
274
|
+
raw = headers.get("Retry-After") or headers.get("retry-after")
|
|
275
|
+
if not raw:
|
|
276
|
+
return None
|
|
277
|
+
try:
|
|
278
|
+
return float(raw)
|
|
279
|
+
except (TypeError, ValueError):
|
|
280
|
+
return None
|
podpislon/_utils.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Internal utilities: rate limiting, retries, request shaping.
|
|
2
|
+
|
|
3
|
+
Nothing in this module is part of the public API; signatures may change
|
|
4
|
+
between minor versions.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import base64
|
|
11
|
+
import time
|
|
12
|
+
from collections import deque
|
|
13
|
+
from contextlib import asynccontextmanager
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, AsyncIterator, Iterable, Mapping, Sequence
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AsyncRateLimiter:
|
|
19
|
+
"""Token-bucket-style limiter capping requests over a sliding window.
|
|
20
|
+
|
|
21
|
+
The Podpislon API allows 4 requests per second per API key. A naive
|
|
22
|
+
``asyncio.sleep`` between calls would either over- or under-shoot when
|
|
23
|
+
requests come in bursts. Tracking timestamps in a deque gives us an exact
|
|
24
|
+
sliding window: we sleep only as long as needed for the oldest request
|
|
25
|
+
to fall outside it.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, rate: int, per: float = 1.0) -> None:
|
|
29
|
+
if rate <= 0:
|
|
30
|
+
raise ValueError("rate must be a positive integer")
|
|
31
|
+
if per <= 0:
|
|
32
|
+
raise ValueError("per must be a positive float (seconds)")
|
|
33
|
+
self._rate = rate
|
|
34
|
+
self._per = per
|
|
35
|
+
self._timestamps: deque[float] = deque()
|
|
36
|
+
self._lock = asyncio.Lock()
|
|
37
|
+
|
|
38
|
+
@asynccontextmanager
|
|
39
|
+
async def slot(self) -> AsyncIterator[None]:
|
|
40
|
+
async with self._lock:
|
|
41
|
+
now = time.monotonic()
|
|
42
|
+
cutoff = now - self._per
|
|
43
|
+
while self._timestamps and self._timestamps[0] <= cutoff:
|
|
44
|
+
self._timestamps.popleft()
|
|
45
|
+
|
|
46
|
+
if len(self._timestamps) >= self._rate:
|
|
47
|
+
wait_for = self._per - (now - self._timestamps[0])
|
|
48
|
+
if wait_for > 0:
|
|
49
|
+
await asyncio.sleep(wait_for)
|
|
50
|
+
now = time.monotonic()
|
|
51
|
+
cutoff = now - self._per
|
|
52
|
+
while self._timestamps and self._timestamps[0] <= cutoff:
|
|
53
|
+
self._timestamps.popleft()
|
|
54
|
+
|
|
55
|
+
self._timestamps.append(time.monotonic())
|
|
56
|
+
yield
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def encode_file_to_base64(source: bytes | str | Path) -> str:
|
|
60
|
+
"""Encode a PDF file or raw bytes into the base64 form expected by the API."""
|
|
61
|
+
|
|
62
|
+
if isinstance(source, (str, Path)):
|
|
63
|
+
path = Path(source)
|
|
64
|
+
if not path.is_file():
|
|
65
|
+
raise FileNotFoundError(f"File not found: {path}")
|
|
66
|
+
data = path.read_bytes()
|
|
67
|
+
elif isinstance(source, (bytes, bytearray)):
|
|
68
|
+
data = bytes(source)
|
|
69
|
+
else:
|
|
70
|
+
raise TypeError(
|
|
71
|
+
f"Unsupported file source: {type(source).__name__}; "
|
|
72
|
+
"expected bytes, str path or pathlib.Path"
|
|
73
|
+
)
|
|
74
|
+
return base64.b64encode(data).decode("ascii")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def decode_base64_to_bytes(value: str) -> bytes:
|
|
78
|
+
"""Decode the base64 string that ``GET /get-file`` returns."""
|
|
79
|
+
|
|
80
|
+
return base64.b64decode(value, validate=False)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def to_form_data(payload: Mapping[str, Any]) -> dict[str, Any]:
|
|
84
|
+
"""Flatten a payload into ``application/x-www-form-urlencoded`` form.
|
|
85
|
+
|
|
86
|
+
Pydantic / dict values that are themselves arrays or mappings are encoded
|
|
87
|
+
using PHP-style bracket keys (``contacts[0][phone]``), which is the format
|
|
88
|
+
Podpislon's PHP backend understands. ``None`` values are dropped so that
|
|
89
|
+
optional fields don't accidentally clobber server-side defaults.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
out: dict[str, Any] = {}
|
|
93
|
+
for key, value in payload.items():
|
|
94
|
+
if value is None:
|
|
95
|
+
continue
|
|
96
|
+
_flatten(key, value, out)
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _flatten(key: str, value: Any, out: dict[str, Any]) -> None:
|
|
101
|
+
if isinstance(value, Mapping):
|
|
102
|
+
for sub_key, sub_value in value.items():
|
|
103
|
+
_flatten(f"{key}[{sub_key}]", sub_value, out)
|
|
104
|
+
elif isinstance(value, (list, tuple, set)) and not isinstance(value, (str, bytes, bytearray)):
|
|
105
|
+
for index, item in enumerate(value):
|
|
106
|
+
_flatten(f"{key}[{index}]", item, out)
|
|
107
|
+
elif isinstance(value, bool):
|
|
108
|
+
# The API expects "Y" for boolean-like flags rather than "true"/"false".
|
|
109
|
+
out[key] = "Y" if value else ""
|
|
110
|
+
else:
|
|
111
|
+
out[key] = value
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def chunked(iterable: Sequence[Any], size: int) -> Iterable[Sequence[Any]]:
|
|
115
|
+
"""Yield successive ``size``-sized chunks of ``iterable``."""
|
|
116
|
+
|
|
117
|
+
if size <= 0:
|
|
118
|
+
raise ValueError("size must be a positive integer")
|
|
119
|
+
for i in range(0, len(iterable), size):
|
|
120
|
+
yield iterable[i : i + size]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def parse_int_header(headers: Mapping[str, str], name: str) -> int | None:
|
|
124
|
+
"""Read an integer header (used for pagination metadata).
|
|
125
|
+
|
|
126
|
+
HTTP header names are case-insensitive but Python ``dict`` lookups are not,
|
|
127
|
+
so we walk the keys ourselves.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
raw = headers.get(name)
|
|
131
|
+
if raw is None:
|
|
132
|
+
target = name.lower()
|
|
133
|
+
for key, value in headers.items():
|
|
134
|
+
if key.lower() == target:
|
|
135
|
+
raw = value
|
|
136
|
+
break
|
|
137
|
+
if raw is None:
|
|
138
|
+
return None
|
|
139
|
+
try:
|
|
140
|
+
return int(raw)
|
|
141
|
+
except (TypeError, ValueError):
|
|
142
|
+
return None
|
podpislon/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '1.0.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (1, 0, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
podpislon/client.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""High-level async client for the Podpislon API.
|
|
2
|
+
|
|
3
|
+
Typical usage::
|
|
4
|
+
|
|
5
|
+
from podpislon import PodpislonClient
|
|
6
|
+
|
|
7
|
+
async with PodpislonClient(api_key="...") as client:
|
|
8
|
+
info = await client.company.get_info()
|
|
9
|
+
async for doc in client.documents.iter_all():
|
|
10
|
+
print(doc.id, doc.name)
|
|
11
|
+
|
|
12
|
+
The client is a thin façade: each remote resource lives on its own
|
|
13
|
+
attribute (``client.documents``, ``client.company``, ``client.payments``)
|
|
14
|
+
and shares a single underlying transport. This keeps the public surface
|
|
15
|
+
discoverable via tab-completion and matches the layout of every
|
|
16
|
+
well-loved Python SDK (``stripe.Customer``, ``boto3.client(...).list_*``).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from types import TracebackType
|
|
22
|
+
from typing import Any, Type
|
|
23
|
+
|
|
24
|
+
import httpx
|
|
25
|
+
|
|
26
|
+
from podpislon._transport import RetryPolicy, Transport
|
|
27
|
+
from podpislon._utils import AsyncRateLimiter
|
|
28
|
+
from podpislon.exceptions import PodpislonConfigurationError
|
|
29
|
+
from podpislon.resources.company import CompanyResource
|
|
30
|
+
from podpislon.resources.documents import DocumentsResource
|
|
31
|
+
from podpislon.resources.payments import PaymentsResource
|
|
32
|
+
|
|
33
|
+
DEFAULT_BASE_URL = "https://podpislon.ru/integration"
|
|
34
|
+
DEFAULT_TIMEOUT = 30.0
|
|
35
|
+
DEFAULT_USER_AGENT = "podpislon-sdk-python (+https://github.com/IceOne-i/podpislon-sdk)"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class PodpislonClient:
|
|
39
|
+
"""Async API client for the Podpislon document-signing service.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
api_key:
|
|
44
|
+
The API key generated in the Podpislon dashboard
|
|
45
|
+
(`Личный кабинет → Интеграции <https://podpislon.ru/lk/integrations>`_).
|
|
46
|
+
base_url:
|
|
47
|
+
Override the API root. Useful only for staging environments.
|
|
48
|
+
timeout:
|
|
49
|
+
Per-request timeout in seconds, or an :class:`httpx.Timeout` for
|
|
50
|
+
fine-grained control.
|
|
51
|
+
max_retries:
|
|
52
|
+
Number of retries for transient failures (``429``, ``5xx``, network
|
|
53
|
+
errors). Set to ``0`` to disable retries.
|
|
54
|
+
rate_limit:
|
|
55
|
+
Maximum requests per second to enforce client-side. The Podpislon API
|
|
56
|
+
documents a 4 RPS limit per key; the SDK matches that by default.
|
|
57
|
+
Set to ``None`` to disable the limiter (e.g. when running tests).
|
|
58
|
+
user_agent:
|
|
59
|
+
Custom ``User-Agent`` header. Defaults to the SDK identifier.
|
|
60
|
+
http_client:
|
|
61
|
+
Inject your own preconfigured :class:`httpx.AsyncClient` (proxy,
|
|
62
|
+
custom transport, mTLS, etc.). When supplied, the SDK will NOT close
|
|
63
|
+
it on exit — that's your responsibility.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
api_key: str,
|
|
69
|
+
*,
|
|
70
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
71
|
+
timeout: float | httpx.Timeout = DEFAULT_TIMEOUT,
|
|
72
|
+
max_retries: int = 3,
|
|
73
|
+
rate_limit: int | None = 4,
|
|
74
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
75
|
+
http_client: httpx.AsyncClient | None = None,
|
|
76
|
+
) -> None:
|
|
77
|
+
if not api_key or not isinstance(api_key, str):
|
|
78
|
+
raise PodpislonConfigurationError(
|
|
79
|
+
"api_key must be a non-empty string. Generate one in the "
|
|
80
|
+
"Podpislon dashboard at https://podpislon.ru/lk/integrations."
|
|
81
|
+
)
|
|
82
|
+
if not base_url:
|
|
83
|
+
raise PodpislonConfigurationError("base_url must be a non-empty string")
|
|
84
|
+
|
|
85
|
+
self._closed = False
|
|
86
|
+
self._transport = Transport(
|
|
87
|
+
api_key=api_key,
|
|
88
|
+
base_url=base_url,
|
|
89
|
+
timeout=timeout,
|
|
90
|
+
retry_policy=RetryPolicy(max_retries=max_retries),
|
|
91
|
+
rate_limiter=AsyncRateLimiter(rate_limit) if rate_limit else None,
|
|
92
|
+
user_agent=user_agent,
|
|
93
|
+
client=http_client,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
self.documents = DocumentsResource(self._transport)
|
|
97
|
+
self.company = CompanyResource(self._transport)
|
|
98
|
+
self.payments = PaymentsResource(self._transport)
|
|
99
|
+
|
|
100
|
+
# ------------------------------------------------------------------
|
|
101
|
+
# Lifecycle
|
|
102
|
+
# ------------------------------------------------------------------
|
|
103
|
+
async def __aenter__(self) -> "PodpislonClient":
|
|
104
|
+
return self
|
|
105
|
+
|
|
106
|
+
async def __aexit__(
|
|
107
|
+
self,
|
|
108
|
+
exc_type: Type[BaseException] | None,
|
|
109
|
+
exc: BaseException | None,
|
|
110
|
+
tb: TracebackType | None,
|
|
111
|
+
) -> None:
|
|
112
|
+
await self.aclose()
|
|
113
|
+
|
|
114
|
+
async def aclose(self) -> None:
|
|
115
|
+
"""Close the underlying HTTP connection pool.
|
|
116
|
+
|
|
117
|
+
Safe to call multiple times; subsequent calls are no-ops.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
if self._closed:
|
|
121
|
+
return
|
|
122
|
+
self._closed = True
|
|
123
|
+
await self._transport.aclose()
|
|
124
|
+
|
|
125
|
+
# ------------------------------------------------------------------
|
|
126
|
+
# Convenience
|
|
127
|
+
# ------------------------------------------------------------------
|
|
128
|
+
@property
|
|
129
|
+
def base_url(self) -> str:
|
|
130
|
+
return self._transport.base_url
|
|
131
|
+
|
|
132
|
+
def __repr__(self) -> str: # pragma: no cover - cosmetic only
|
|
133
|
+
return f"PodpislonClient(base_url={self.base_url!r})"
|
|
134
|
+
|
|
135
|
+
# Allow `await client(...)` style ergonomic helpers in the future
|
|
136
|
+
# without breaking back-compat.
|
|
137
|
+
async def request(self, method: str, path: str, **kwargs: Any) -> Any:
|
|
138
|
+
"""Escape hatch for endpoints not yet wrapped by the SDK.
|
|
139
|
+
|
|
140
|
+
Returns the raw decoded JSON body. Use sparingly — prefer the typed
|
|
141
|
+
resource methods.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
response = await self._transport.request(method, path, **kwargs)
|
|
145
|
+
return response.json_body if response.is_json else response.text
|