pandafile 0.2.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.
- pandafile-0.2.0/.gitignore +8 -0
- pandafile-0.2.0/LICENSE +21 -0
- pandafile-0.2.0/PKG-INFO +169 -0
- pandafile-0.2.0/README.md +136 -0
- pandafile-0.2.0/pandafile/__init__.py +37 -0
- pandafile-0.2.0/pandafile/_client.py +243 -0
- pandafile-0.2.0/pandafile/_errors.py +115 -0
- pandafile-0.2.0/pandafile/_files.py +159 -0
- pandafile-0.2.0/pandafile/_pagination.py +128 -0
- pandafile-0.2.0/pandafile/_resources.py +288 -0
- pandafile-0.2.0/pandafile/_send.py +284 -0
- pandafile-0.2.0/pandafile/_tus.py +290 -0
- pandafile-0.2.0/pandafile/_version.py +1 -0
- pandafile-0.2.0/pandafile/py.typed +0 -0
- pandafile-0.2.0/pandafile/types.py +753 -0
- pandafile-0.2.0/pandafile/webhooks.py +69 -0
- pandafile-0.2.0/pyproject.toml +49 -0
- pandafile-0.2.0/tests/conftest.py +130 -0
- pandafile-0.2.0/tests/test_client.py +207 -0
- pandafile-0.2.0/tests/test_send.py +89 -0
- pandafile-0.2.0/tests/test_tus.py +157 -0
- pandafile-0.2.0/tests/test_webhooks.py +66 -0
pandafile-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 3XAYA LTD (Pandafile)
|
|
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.
|
pandafile-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pandafile
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Official Pandafile SDK: send large files with resumable uploads, file requests, e-signatures and webhooks.
|
|
5
|
+
Project-URL: Homepage, https://pandafile.co/developers/sdks
|
|
6
|
+
Project-URL: Documentation, https://pandafile.co/developers
|
|
7
|
+
Project-URL: API reference, https://pandafile.co/developers/api
|
|
8
|
+
Project-URL: Repository, https://github.com/pandafileco/pandafile-python
|
|
9
|
+
Project-URL: Issues, https://github.com/pandafileco/pandafile-python/issues
|
|
10
|
+
Author-email: 3XAYA LTD <hello@pandafile.co>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: file transfer,large files,pandafile,resumable,sdk,tus,upload,webhooks
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Topic :: Communications :: File Sharing
|
|
26
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.9
|
|
29
|
+
Requires-Dist: httpx<1,>=0.24
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# pandafile
|
|
35
|
+
|
|
36
|
+
The official Python SDK for [Pandafile](https://pandafile.co): send files of any size with resumable uploads, collect
|
|
37
|
+
files with file requests, get documents signed and react to webhooks.
|
|
38
|
+
|
|
39
|
+
- Python 3.9+, one dependency (`httpx`). Sync **and** async clients.
|
|
40
|
+
- `transfers.send()` does everything: create, upload (tus, chunked, parallel, resumable), complete, return the link.
|
|
41
|
+
- Automatic `Idempotency-Key` on every POST/PATCH/PUT, retries with backoff on 429/5xx honouring `Retry-After`,
|
|
42
|
+
typed errors, auto-pagination, webhook signature verification, TypedDicts generated from the OpenAPI document.
|
|
43
|
+
|
|
44
|
+
The API is included with Pandafile Pro and Team. Create a key in **Dashboard → Domain & API**.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
pip install pandafile
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Quick start
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from pandafile import Pandafile
|
|
56
|
+
|
|
57
|
+
pf = Pandafile() # reads PANDAFILE_API_KEY (pf_live_… or pf_test_…)
|
|
58
|
+
|
|
59
|
+
result = pf.transfers.send(
|
|
60
|
+
["final-cut.mov", "stills/"], # folders keep their structure
|
|
61
|
+
recipients=["client@example.com"],
|
|
62
|
+
title="Final cut",
|
|
63
|
+
on_progress=lambda p: print(f"{p.percent:.1f} %"),
|
|
64
|
+
)
|
|
65
|
+
print(result.url) # https://pandafile.co/d/k3x9q2m7ab
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Files can be paths, `(name, bytes)`, `{"name": ..., "data": ...}`, `{"path": ..., "name": ...}` or binary file objects.
|
|
69
|
+
|
|
70
|
+
### Async
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import asyncio
|
|
74
|
+
from pandafile import AsyncPandafile
|
|
75
|
+
|
|
76
|
+
async def main():
|
|
77
|
+
async with AsyncPandafile() as pf:
|
|
78
|
+
result = await pf.transfers.send(["film.mov"])
|
|
79
|
+
async for t in pf.transfers.list():
|
|
80
|
+
print(t["id"], t["title"])
|
|
81
|
+
|
|
82
|
+
asyncio.run(main())
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Resumable sends
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import json, pathlib
|
|
89
|
+
p = pathlib.Path("send-state.json")
|
|
90
|
+
state = json.loads(p.read_text()) if p.exists() else None
|
|
91
|
+
result = pf.transfers.send(["huge.mxf"], state=state, on_state=lambda s: p.write_text(json.dumps(s)))
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Finished files are skipped and the unfinished one continues at the byte the server has.
|
|
95
|
+
|
|
96
|
+
## Every endpoint
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
pf.me.retrieve()
|
|
100
|
+
for t in pf.transfers.list(view="active"): # auto-pagination
|
|
101
|
+
...
|
|
102
|
+
page = pf.transfers.list(limit=50).page() # one page: page.data, page.has_more, page.next_page()
|
|
103
|
+
pf.transfers.retrieve("k3x9q2m7ab")
|
|
104
|
+
pf.transfers.update("k3x9q2m7ab", title="v2", password="blue-river-42")
|
|
105
|
+
pf.transfers.add_recipients("k3x9q2m7ab", ["producer@example.com"])
|
|
106
|
+
pf.transfers.delete("k3x9q2m7ab")
|
|
107
|
+
|
|
108
|
+
pf.requests.create(title="Photos from the wedding")
|
|
109
|
+
draft = pf.signatures.create("nda.pdf")
|
|
110
|
+
pf.signatures.send(draft["id"], signers=[{"name": "Ada", "email": "ada@example.com"}],
|
|
111
|
+
fields=[{"signer": 0, "kind": "signature", "page": 0, "x": 0.1, "y": 0.8, "w": 0.3, "h": 0.06}])
|
|
112
|
+
pf.branding.update(name="Studio Nord", color="#1F7A4D")
|
|
113
|
+
pf.team.invite(["sam@example.com"])
|
|
114
|
+
pf.events.list(since="2026-11-25T00:00:00Z", type="transfer.downloaded")
|
|
115
|
+
pf.hooks.create(url="https://example.com/pandafile-webhook", events=["transfer.ready"])
|
|
116
|
+
pf.request("GET", "/me") # anything else, by hand
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Responses are plain dicts; `pandafile.types` has a `TypedDict` for each (`Transfer`, `TransferDetail`, `Event`, …).
|
|
120
|
+
|
|
121
|
+
## Errors
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from pandafile import NotFoundError, PandafileError
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
pf.transfers.retrieve("nope1234")
|
|
128
|
+
except NotFoundError as e:
|
|
129
|
+
print(e.code) # resource_missing
|
|
130
|
+
except PandafileError as e:
|
|
131
|
+
print(e.type, e.code, e.status, e.request_id, e.param)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Classes: `InvalidRequestError` (`NotFoundError`), `AuthenticationError`, `PermissionDeniedError`, `IdempotencyError`,
|
|
135
|
+
`RateLimitError` (`retry_after`), `APIError`, `APIConnectionError`, `UploadError`, `SignatureVerificationError`.
|
|
136
|
+
|
|
137
|
+
## Webhooks
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from flask import Flask, request, abort
|
|
141
|
+
from pandafile import webhooks
|
|
142
|
+
|
|
143
|
+
app = Flask(__name__)
|
|
144
|
+
|
|
145
|
+
@app.post("/pandafile-webhook")
|
|
146
|
+
def hook():
|
|
147
|
+
body = request.get_data() # the raw bytes
|
|
148
|
+
if not webhooks.verify(body, request.headers.get("Pandafile-Signature"), SECRET, tolerance=300):
|
|
149
|
+
abort(400)
|
|
150
|
+
event = request.get_json()
|
|
151
|
+
return "", 200
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
`webhooks.construct_event(body, header, secret)` verifies and parses (raises `SignatureVerificationError`).
|
|
155
|
+
`Pandafile.webhooks` is the same module.
|
|
156
|
+
|
|
157
|
+
## Options
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
Pandafile(api_key="pf_live_…", base_url="https://pandafile.co", max_retries=3, timeout=60.0, http_client=None)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`pf.last_response["headers"]` holds the `ratelimit-*` headers of the last call.
|
|
164
|
+
|
|
165
|
+
## Links
|
|
166
|
+
|
|
167
|
+
- Guide: https://pandafile.co/developers
|
|
168
|
+
- API reference: https://pandafile.co/developers/api
|
|
169
|
+
- SDKs and CLI: https://pandafile.co/developers/sdks
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# pandafile
|
|
2
|
+
|
|
3
|
+
The official Python SDK for [Pandafile](https://pandafile.co): send files of any size with resumable uploads, collect
|
|
4
|
+
files with file requests, get documents signed and react to webhooks.
|
|
5
|
+
|
|
6
|
+
- Python 3.9+, one dependency (`httpx`). Sync **and** async clients.
|
|
7
|
+
- `transfers.send()` does everything: create, upload (tus, chunked, parallel, resumable), complete, return the link.
|
|
8
|
+
- Automatic `Idempotency-Key` on every POST/PATCH/PUT, retries with backoff on 429/5xx honouring `Retry-After`,
|
|
9
|
+
typed errors, auto-pagination, webhook signature verification, TypedDicts generated from the OpenAPI document.
|
|
10
|
+
|
|
11
|
+
The API is included with Pandafile Pro and Team. Create a key in **Dashboard → Domain & API**.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
pip install pandafile
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick start
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from pandafile import Pandafile
|
|
23
|
+
|
|
24
|
+
pf = Pandafile() # reads PANDAFILE_API_KEY (pf_live_… or pf_test_…)
|
|
25
|
+
|
|
26
|
+
result = pf.transfers.send(
|
|
27
|
+
["final-cut.mov", "stills/"], # folders keep their structure
|
|
28
|
+
recipients=["client@example.com"],
|
|
29
|
+
title="Final cut",
|
|
30
|
+
on_progress=lambda p: print(f"{p.percent:.1f} %"),
|
|
31
|
+
)
|
|
32
|
+
print(result.url) # https://pandafile.co/d/k3x9q2m7ab
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Files can be paths, `(name, bytes)`, `{"name": ..., "data": ...}`, `{"path": ..., "name": ...}` or binary file objects.
|
|
36
|
+
|
|
37
|
+
### Async
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import asyncio
|
|
41
|
+
from pandafile import AsyncPandafile
|
|
42
|
+
|
|
43
|
+
async def main():
|
|
44
|
+
async with AsyncPandafile() as pf:
|
|
45
|
+
result = await pf.transfers.send(["film.mov"])
|
|
46
|
+
async for t in pf.transfers.list():
|
|
47
|
+
print(t["id"], t["title"])
|
|
48
|
+
|
|
49
|
+
asyncio.run(main())
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Resumable sends
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import json, pathlib
|
|
56
|
+
p = pathlib.Path("send-state.json")
|
|
57
|
+
state = json.loads(p.read_text()) if p.exists() else None
|
|
58
|
+
result = pf.transfers.send(["huge.mxf"], state=state, on_state=lambda s: p.write_text(json.dumps(s)))
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Finished files are skipped and the unfinished one continues at the byte the server has.
|
|
62
|
+
|
|
63
|
+
## Every endpoint
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
pf.me.retrieve()
|
|
67
|
+
for t in pf.transfers.list(view="active"): # auto-pagination
|
|
68
|
+
...
|
|
69
|
+
page = pf.transfers.list(limit=50).page() # one page: page.data, page.has_more, page.next_page()
|
|
70
|
+
pf.transfers.retrieve("k3x9q2m7ab")
|
|
71
|
+
pf.transfers.update("k3x9q2m7ab", title="v2", password="blue-river-42")
|
|
72
|
+
pf.transfers.add_recipients("k3x9q2m7ab", ["producer@example.com"])
|
|
73
|
+
pf.transfers.delete("k3x9q2m7ab")
|
|
74
|
+
|
|
75
|
+
pf.requests.create(title="Photos from the wedding")
|
|
76
|
+
draft = pf.signatures.create("nda.pdf")
|
|
77
|
+
pf.signatures.send(draft["id"], signers=[{"name": "Ada", "email": "ada@example.com"}],
|
|
78
|
+
fields=[{"signer": 0, "kind": "signature", "page": 0, "x": 0.1, "y": 0.8, "w": 0.3, "h": 0.06}])
|
|
79
|
+
pf.branding.update(name="Studio Nord", color="#1F7A4D")
|
|
80
|
+
pf.team.invite(["sam@example.com"])
|
|
81
|
+
pf.events.list(since="2026-11-25T00:00:00Z", type="transfer.downloaded")
|
|
82
|
+
pf.hooks.create(url="https://example.com/pandafile-webhook", events=["transfer.ready"])
|
|
83
|
+
pf.request("GET", "/me") # anything else, by hand
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Responses are plain dicts; `pandafile.types` has a `TypedDict` for each (`Transfer`, `TransferDetail`, `Event`, …).
|
|
87
|
+
|
|
88
|
+
## Errors
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from pandafile import NotFoundError, PandafileError
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
pf.transfers.retrieve("nope1234")
|
|
95
|
+
except NotFoundError as e:
|
|
96
|
+
print(e.code) # resource_missing
|
|
97
|
+
except PandafileError as e:
|
|
98
|
+
print(e.type, e.code, e.status, e.request_id, e.param)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Classes: `InvalidRequestError` (`NotFoundError`), `AuthenticationError`, `PermissionDeniedError`, `IdempotencyError`,
|
|
102
|
+
`RateLimitError` (`retry_after`), `APIError`, `APIConnectionError`, `UploadError`, `SignatureVerificationError`.
|
|
103
|
+
|
|
104
|
+
## Webhooks
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from flask import Flask, request, abort
|
|
108
|
+
from pandafile import webhooks
|
|
109
|
+
|
|
110
|
+
app = Flask(__name__)
|
|
111
|
+
|
|
112
|
+
@app.post("/pandafile-webhook")
|
|
113
|
+
def hook():
|
|
114
|
+
body = request.get_data() # the raw bytes
|
|
115
|
+
if not webhooks.verify(body, request.headers.get("Pandafile-Signature"), SECRET, tolerance=300):
|
|
116
|
+
abort(400)
|
|
117
|
+
event = request.get_json()
|
|
118
|
+
return "", 200
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`webhooks.construct_event(body, header, secret)` verifies and parses (raises `SignatureVerificationError`).
|
|
122
|
+
`Pandafile.webhooks` is the same module.
|
|
123
|
+
|
|
124
|
+
## Options
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
Pandafile(api_key="pf_live_…", base_url="https://pandafile.co", max_retries=3, timeout=60.0, http_client=None)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`pf.last_response["headers"]` holds the `ratelimit-*` headers of the last call.
|
|
131
|
+
|
|
132
|
+
## Links
|
|
133
|
+
|
|
134
|
+
- Guide: https://pandafile.co/developers
|
|
135
|
+
- API reference: https://pandafile.co/developers/api
|
|
136
|
+
- SDKs and CLI: https://pandafile.co/developers/sdks
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Pandafile – the official Python SDK. https://pandafile.co/developers/sdks
|
|
2
|
+
|
|
3
|
+
from pandafile import Pandafile
|
|
4
|
+
pf = Pandafile() # PANDAFILE_API_KEY
|
|
5
|
+
print(pf.transfers.send(["film.mov"]).url)
|
|
6
|
+
"""
|
|
7
|
+
from . import types, webhooks
|
|
8
|
+
from ._client import DEFAULT_BASE_URL, AsyncPandafile, Pandafile
|
|
9
|
+
from ._errors import (
|
|
10
|
+
APIConnectionError,
|
|
11
|
+
APIError,
|
|
12
|
+
AuthenticationError,
|
|
13
|
+
IdempotencyError,
|
|
14
|
+
InvalidRequestError,
|
|
15
|
+
NotFoundError,
|
|
16
|
+
PandafileError,
|
|
17
|
+
PermissionDeniedError,
|
|
18
|
+
RateLimitError,
|
|
19
|
+
SignatureVerificationError,
|
|
20
|
+
UploadError,
|
|
21
|
+
)
|
|
22
|
+
from ._files import PreparedFile, prepare_files
|
|
23
|
+
from ._pagination import AsyncPage, AsyncPager, Page, SyncPage, SyncPager
|
|
24
|
+
from ._send import FileProgress, SendProgress, SendResult
|
|
25
|
+
from ._tus import DEFAULT_CHUNK_SIZE, TusResult, encode_metadata, tus_upload, tus_upload_async
|
|
26
|
+
from ._version import __version__
|
|
27
|
+
from .types import API_VERSION, EVENT_TYPES
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"Pandafile", "AsyncPandafile", "DEFAULT_BASE_URL", "API_VERSION", "EVENT_TYPES", "__version__",
|
|
31
|
+
"webhooks", "types",
|
|
32
|
+
"PandafileError", "InvalidRequestError", "NotFoundError", "AuthenticationError", "PermissionDeniedError", "IdempotencyError",
|
|
33
|
+
"RateLimitError", "APIError", "APIConnectionError", "SignatureVerificationError", "UploadError",
|
|
34
|
+
"Page", "SyncPage", "AsyncPage", "SyncPager", "AsyncPager",
|
|
35
|
+
"SendProgress", "SendResult", "FileProgress", "PreparedFile", "prepare_files",
|
|
36
|
+
"tus_upload", "tus_upload_async", "encode_metadata", "TusResult", "DEFAULT_CHUNK_SIZE",
|
|
37
|
+
]
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json as _json
|
|
5
|
+
import os
|
|
6
|
+
import platform
|
|
7
|
+
import random
|
|
8
|
+
import time
|
|
9
|
+
import uuid
|
|
10
|
+
from email.utils import parsedate_to_datetime
|
|
11
|
+
from typing import Any, Dict, Mapping, Optional, Tuple
|
|
12
|
+
from urllib.parse import urlencode
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from . import webhooks as _webhooks
|
|
17
|
+
from ._errors import APIConnectionError, PandafileError, error_from_response
|
|
18
|
+
from ._pagination import AsyncPager, SyncPager
|
|
19
|
+
from ._resources import Branding, Domains, Events, FileRequests, Hooks, Keys, Me, Signatures, Team, Transfers
|
|
20
|
+
from ._send import send_async, send_sync
|
|
21
|
+
from ._version import __version__
|
|
22
|
+
from .types import API_VERSION
|
|
23
|
+
|
|
24
|
+
DEFAULT_BASE_URL = "https://pandafile.co"
|
|
25
|
+
RETRY_STATUS = {408, 429, 500, 502, 503, 504}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _retry_after(headers: Mapping[str, str]) -> Optional[float]:
|
|
29
|
+
v = headers.get("retry-after")
|
|
30
|
+
if not v:
|
|
31
|
+
return None
|
|
32
|
+
try:
|
|
33
|
+
return max(0.0, float(v))
|
|
34
|
+
except ValueError:
|
|
35
|
+
try:
|
|
36
|
+
return max(0.0, parsedate_to_datetime(v).timestamp() - time.time())
|
|
37
|
+
except (TypeError, ValueError):
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _backoff(attempt: int, base: float = 0.5, cap: float = 8.0) -> float:
|
|
42
|
+
d = min(cap, base * (2 ** attempt))
|
|
43
|
+
return d / 2 + random.random() * d / 2
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _parse(r: httpx.Response) -> Any:
|
|
47
|
+
if not r.content:
|
|
48
|
+
return None
|
|
49
|
+
try:
|
|
50
|
+
return r.json()
|
|
51
|
+
except ValueError:
|
|
52
|
+
return r.text
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class _Base:
|
|
56
|
+
def __init__(self, api_key: Optional[str], base_url: Optional[str], api_version: Optional[str], max_retries: int, timeout: float, app_info: Optional[str]) -> None:
|
|
57
|
+
key = api_key or os.environ.get("PANDAFILE_API_KEY")
|
|
58
|
+
if not key:
|
|
59
|
+
raise PandafileError("No API key: pass api_key=... or set PANDAFILE_API_KEY.", type="authentication_error", code="api_key_missing")
|
|
60
|
+
self.api_key = key
|
|
61
|
+
self.base_url = (base_url or os.environ.get("PANDAFILE_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
62
|
+
self.api_version = api_version or API_VERSION
|
|
63
|
+
self.max_retries = max_retries
|
|
64
|
+
self.timeout = timeout
|
|
65
|
+
self.user_agent = f"pandafile-python/{__version__} python/{platform.python_version()}" + (f" {app_info}" if app_info else "")
|
|
66
|
+
self.last_response: Optional[Dict[str, Any]] = None
|
|
67
|
+
self.me = Me(self)
|
|
68
|
+
self.keys = Keys(self)
|
|
69
|
+
self.domains = Domains(self)
|
|
70
|
+
self.transfers = Transfers(self)
|
|
71
|
+
self.requests = FileRequests(self)
|
|
72
|
+
self.signatures = Signatures(self)
|
|
73
|
+
self.branding = Branding(self)
|
|
74
|
+
self.team = Team(self)
|
|
75
|
+
self.events = Events(self)
|
|
76
|
+
self.hooks = Hooks(self)
|
|
77
|
+
|
|
78
|
+
webhooks = _webhooks
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def livemode(self) -> bool:
|
|
82
|
+
return not self.api_key.startswith("pf_test_")
|
|
83
|
+
|
|
84
|
+
def _url(self, path: str, query: Optional[Mapping[str, Any]]) -> str:
|
|
85
|
+
url = f"{self.base_url}/api/v1{path}"
|
|
86
|
+
q = {k: ("true" if v is True else "false" if v is False else v) for k, v in (query or {}).items() if v is not None and v != ""}
|
|
87
|
+
return url + ("?" + urlencode(q) if q else "")
|
|
88
|
+
|
|
89
|
+
def _prepare(self, method: str, json: Any, content: Optional[bytes], content_type: Optional[str], binary: bool,
|
|
90
|
+
idempotency_key: Optional[str], headers: Optional[Mapping[str, str]]) -> Tuple[Dict[str, str], Optional[bytes]]:
|
|
91
|
+
h = {
|
|
92
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
93
|
+
"Pandafile-Version": self.api_version,
|
|
94
|
+
"Accept": "*/*" if binary else "application/json",
|
|
95
|
+
"User-Agent": self.user_agent,
|
|
96
|
+
}
|
|
97
|
+
body: Optional[bytes] = None
|
|
98
|
+
if content is not None:
|
|
99
|
+
h["Content-Type"] = content_type or "application/octet-stream"
|
|
100
|
+
body = content
|
|
101
|
+
elif json is not None:
|
|
102
|
+
h["Content-Type"] = "application/json"
|
|
103
|
+
body = _json.dumps(json).encode("utf-8")
|
|
104
|
+
if method in ("POST", "PATCH", "PUT"):
|
|
105
|
+
h["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
|
|
106
|
+
h.update(headers or {})
|
|
107
|
+
return h, body
|
|
108
|
+
|
|
109
|
+
def _handle(self, r: httpx.Response, binary: bool) -> Tuple[bool, Any, Optional[PandafileError], float]:
|
|
110
|
+
h = {k.lower(): v for k, v in r.headers.items()}
|
|
111
|
+
self.last_response = {"status": r.status_code, "headers": h, "request_id": h.get("x-request-id")}
|
|
112
|
+
if r.status_code < 300:
|
|
113
|
+
return True, (r.content if binary else _parse(r)), None, 0.0
|
|
114
|
+
err = error_from_response(r.status_code, _parse(r), h)
|
|
115
|
+
retryable = r.status_code in RETRY_STATUS or err.code == "idempotency_key_in_use"
|
|
116
|
+
ra = _retry_after(h)
|
|
117
|
+
return False, retryable, err, (min(ra, 60.0) if ra is not None else -1.0)
|
|
118
|
+
|
|
119
|
+
def _connection_error(self, e: Exception) -> APIConnectionError:
|
|
120
|
+
timeout = isinstance(e, httpx.TimeoutException)
|
|
121
|
+
return APIConnectionError(f"Request timed out" if timeout else f"Could not reach {self.base_url}: {e}",
|
|
122
|
+
type="connection_error", code="timeout" if timeout else "connection_failed")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class Pandafile(_Base):
|
|
126
|
+
"""The sync client::
|
|
127
|
+
|
|
128
|
+
from pandafile import Pandafile
|
|
129
|
+
pf = Pandafile("pf_live_...") # or PANDAFILE_API_KEY
|
|
130
|
+
result = pf.transfers.send(["film.mov", "stills/"], recipients=["client@example.com"])
|
|
131
|
+
print(result.url)
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None, api_version: Optional[str] = None,
|
|
135
|
+
max_retries: int = 3, timeout: float = 60.0, http_client: Optional[httpx.Client] = None, app_info: Optional[str] = None) -> None:
|
|
136
|
+
super().__init__(api_key, base_url, api_version, max_retries, timeout, app_info)
|
|
137
|
+
self._own_http = http_client is None
|
|
138
|
+
self._http = http_client or httpx.Client(timeout=httpx.Timeout(timeout, connect=min(timeout, 30.0)), follow_redirects=False)
|
|
139
|
+
|
|
140
|
+
def request(self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, json: Any = None, content: Optional[bytes] = None,
|
|
141
|
+
content_type: Optional[str] = None, binary: bool = False, idempotency_key: Optional[str] = None,
|
|
142
|
+
headers: Optional[Mapping[str, str]] = None, max_retries: Optional[int] = None, timeout: Optional[float] = None) -> Any:
|
|
143
|
+
"""Any API call: ``pf.request("GET", "/me")``. POST/PATCH/PUT get an Idempotency-Key reused across retries."""
|
|
144
|
+
method = method.upper()
|
|
145
|
+
h, body = self._prepare(method, json, content, content_type, binary, idempotency_key, headers)
|
|
146
|
+
url = self._url(path, query)
|
|
147
|
+
retries = self.max_retries if max_retries is None else max_retries
|
|
148
|
+
attempt = 0
|
|
149
|
+
while True:
|
|
150
|
+
try:
|
|
151
|
+
r = self._http.request(method, url, headers=h, content=body, timeout=timeout if timeout is not None else self.timeout)
|
|
152
|
+
except httpx.TransportError as e:
|
|
153
|
+
if attempt < retries:
|
|
154
|
+
time.sleep(_backoff(attempt))
|
|
155
|
+
attempt += 1
|
|
156
|
+
continue
|
|
157
|
+
raise self._connection_error(e) from e
|
|
158
|
+
ok, value, err, wait = self._handle(r, binary)
|
|
159
|
+
if ok:
|
|
160
|
+
return value
|
|
161
|
+
assert err is not None
|
|
162
|
+
if value and attempt < retries:
|
|
163
|
+
time.sleep(wait if wait >= 0 else _backoff(attempt))
|
|
164
|
+
attempt += 1
|
|
165
|
+
continue
|
|
166
|
+
raise err
|
|
167
|
+
|
|
168
|
+
def list(self, path: str, params: Optional[Mapping[str, Any]] = None) -> SyncPager:
|
|
169
|
+
p = dict(params or {})
|
|
170
|
+
start = p.pop("starting_after", None)
|
|
171
|
+
return SyncPager(lambda after: self.request("GET", path, query={**p, "starting_after": after}), start)
|
|
172
|
+
|
|
173
|
+
def _send(self, files: Any, **options: Any) -> Any:
|
|
174
|
+
return send_sync(self, files, **options)
|
|
175
|
+
|
|
176
|
+
def close(self) -> None:
|
|
177
|
+
if self._own_http:
|
|
178
|
+
self._http.close()
|
|
179
|
+
|
|
180
|
+
def __enter__(self) -> "Pandafile":
|
|
181
|
+
return self
|
|
182
|
+
|
|
183
|
+
def __exit__(self, *exc: Any) -> None:
|
|
184
|
+
self.close()
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class AsyncPandafile(_Base):
|
|
188
|
+
"""The async client (same resources; methods are awaitable, lists support ``async for``)::
|
|
189
|
+
|
|
190
|
+
async with AsyncPandafile() as pf:
|
|
191
|
+
result = await pf.transfers.send(["film.mov"])
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None, api_version: Optional[str] = None,
|
|
195
|
+
max_retries: int = 3, timeout: float = 60.0, http_client: Optional[httpx.AsyncClient] = None, app_info: Optional[str] = None) -> None:
|
|
196
|
+
super().__init__(api_key, base_url, api_version, max_retries, timeout, app_info)
|
|
197
|
+
self._own_http = http_client is None
|
|
198
|
+
self._http = http_client or httpx.AsyncClient(timeout=httpx.Timeout(timeout, connect=min(timeout, 30.0)), follow_redirects=False)
|
|
199
|
+
|
|
200
|
+
async def request(self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, json: Any = None, content: Optional[bytes] = None,
|
|
201
|
+
content_type: Optional[str] = None, binary: bool = False, idempotency_key: Optional[str] = None,
|
|
202
|
+
headers: Optional[Mapping[str, str]] = None, max_retries: Optional[int] = None, timeout: Optional[float] = None) -> Any:
|
|
203
|
+
method = method.upper()
|
|
204
|
+
h, body = self._prepare(method, json, content, content_type, binary, idempotency_key, headers)
|
|
205
|
+
url = self._url(path, query)
|
|
206
|
+
retries = self.max_retries if max_retries is None else max_retries
|
|
207
|
+
attempt = 0
|
|
208
|
+
while True:
|
|
209
|
+
try:
|
|
210
|
+
r = await self._http.request(method, url, headers=h, content=body, timeout=timeout if timeout is not None else self.timeout)
|
|
211
|
+
except httpx.TransportError as e:
|
|
212
|
+
if attempt < retries:
|
|
213
|
+
await asyncio.sleep(_backoff(attempt))
|
|
214
|
+
attempt += 1
|
|
215
|
+
continue
|
|
216
|
+
raise self._connection_error(e) from e
|
|
217
|
+
ok, value, err, wait = self._handle(r, binary)
|
|
218
|
+
if ok:
|
|
219
|
+
return value
|
|
220
|
+
assert err is not None
|
|
221
|
+
if value and attempt < retries:
|
|
222
|
+
await asyncio.sleep(wait if wait >= 0 else _backoff(attempt))
|
|
223
|
+
attempt += 1
|
|
224
|
+
continue
|
|
225
|
+
raise err
|
|
226
|
+
|
|
227
|
+
def list(self, path: str, params: Optional[Mapping[str, Any]] = None) -> AsyncPager:
|
|
228
|
+
p = dict(params or {})
|
|
229
|
+
start = p.pop("starting_after", None)
|
|
230
|
+
return AsyncPager(lambda after: self.request("GET", path, query={**p, "starting_after": after}), start)
|
|
231
|
+
|
|
232
|
+
async def _send(self, files: Any, **options: Any) -> Any:
|
|
233
|
+
return await send_async(self, files, **options)
|
|
234
|
+
|
|
235
|
+
async def aclose(self) -> None:
|
|
236
|
+
if self._own_http:
|
|
237
|
+
await self._http.aclose()
|
|
238
|
+
|
|
239
|
+
async def __aenter__(self) -> "AsyncPandafile":
|
|
240
|
+
return self
|
|
241
|
+
|
|
242
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
243
|
+
await self.aclose()
|