argoshot 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.
- argoshot/__init__.py +24 -0
- argoshot/_client.py +204 -0
- argoshot/py.typed +0 -0
- argoshot-0.1.0.dist-info/METADATA +124 -0
- argoshot-0.1.0.dist-info/RECORD +7 -0
- argoshot-0.1.0.dist-info/WHEEL +4 -0
- argoshot-0.1.0.dist-info/licenses/LICENSE +21 -0
argoshot/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Argoshot: a small client for the Argoshot screenshot API (https://argoshot.com/docs). Standard library only."""
|
|
2
|
+
|
|
3
|
+
from ._client import (
|
|
4
|
+
DEFAULT_BASE_URL,
|
|
5
|
+
Argoshot,
|
|
6
|
+
ArgoshotError,
|
|
7
|
+
TakeOptions,
|
|
8
|
+
build_query,
|
|
9
|
+
parse_error,
|
|
10
|
+
sign,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.0"
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"DEFAULT_BASE_URL",
|
|
17
|
+
"Argoshot",
|
|
18
|
+
"ArgoshotError",
|
|
19
|
+
"TakeOptions",
|
|
20
|
+
"build_query",
|
|
21
|
+
"parse_error",
|
|
22
|
+
"sign",
|
|
23
|
+
"__version__",
|
|
24
|
+
]
|
argoshot/_client.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import json
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence, TypedDict, Union
|
|
10
|
+
|
|
11
|
+
DEFAULT_BASE_URL = "https://api.argoshot.com"
|
|
12
|
+
_VERSION = "0.1.0"
|
|
13
|
+
_CLIENT_OWN = ("access_key", "signature")
|
|
14
|
+
|
|
15
|
+
OptionValue = Union[str, int, float, bool, None, Sequence[Union[str, int, float, bool]]]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TakeOptions(TypedDict, total=False):
|
|
19
|
+
"""The common options, typed. Any other option of https://argoshot.com/docs/options is accepted by name."""
|
|
20
|
+
|
|
21
|
+
url: str
|
|
22
|
+
html: str
|
|
23
|
+
markdown: str
|
|
24
|
+
format: str
|
|
25
|
+
viewport_width: int
|
|
26
|
+
viewport_height: int
|
|
27
|
+
viewport_device: str
|
|
28
|
+
device_scale_factor: float
|
|
29
|
+
full_page: bool
|
|
30
|
+
block_cookie_banners: bool
|
|
31
|
+
block_ads: bool
|
|
32
|
+
dark_mode: bool
|
|
33
|
+
selector: str
|
|
34
|
+
cache: bool
|
|
35
|
+
cache_ttl: int
|
|
36
|
+
image_quality: int
|
|
37
|
+
delay: int
|
|
38
|
+
timeout: int
|
|
39
|
+
wait_until: List[str]
|
|
40
|
+
hide_selectors: List[str]
|
|
41
|
+
response_type: str
|
|
42
|
+
webhook_url: str
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ArgoshotError(Exception):
|
|
46
|
+
"""An error the API answered (its error_code and error_message), or a response that was not the API's."""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
code: str,
|
|
51
|
+
message: str,
|
|
52
|
+
status: int = 0,
|
|
53
|
+
documentation_url: Optional[str] = None,
|
|
54
|
+
upgrade_url: Optional[str] = None,
|
|
55
|
+
returned_status_code: Optional[int] = None,
|
|
56
|
+
matched_string: Optional[str] = None,
|
|
57
|
+
retry_after: Optional[int] = None,
|
|
58
|
+
body: Optional[str] = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
super().__init__(message)
|
|
61
|
+
self.code = code
|
|
62
|
+
self.message = message
|
|
63
|
+
self.status = status
|
|
64
|
+
self.documentation_url = documentation_url
|
|
65
|
+
self.upgrade_url = upgrade_url
|
|
66
|
+
self.returned_status_code = returned_status_code
|
|
67
|
+
self.matched_string = matched_string
|
|
68
|
+
self.retry_after = retry_after
|
|
69
|
+
self.body = body
|
|
70
|
+
|
|
71
|
+
def __str__(self) -> str:
|
|
72
|
+
return f"{self.code}: {self.message}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Argoshot:
|
|
76
|
+
"""A client for the Argoshot API.
|
|
77
|
+
|
|
78
|
+
>>> client = Argoshot("ACCESS_KEY", secret_key="SECRET_KEY")
|
|
79
|
+
>>> png = client.take(url="https://example.com", format="png")
|
|
80
|
+
>>> og_image = client.url(url="https://example.com", viewport_width=1200, viewport_height=630)
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
access_key: str,
|
|
86
|
+
secret_key: Optional[str] = None,
|
|
87
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
88
|
+
timeout: float = 120.0,
|
|
89
|
+
) -> None:
|
|
90
|
+
if not access_key:
|
|
91
|
+
raise ValueError("Argoshot: an access key is required")
|
|
92
|
+
self.access_key = access_key
|
|
93
|
+
self.secret_key = secret_key or None
|
|
94
|
+
self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
|
95
|
+
self.timeout = timeout
|
|
96
|
+
|
|
97
|
+
def url(self, options: Optional[Mapping[str, OptionValue]] = None, /, **kwargs: OptionValue) -> str:
|
|
98
|
+
"""A GET /take URL for these options (for <img src> or og:image), signed when a secret key is set.
|
|
99
|
+
|
|
100
|
+
The access key is in the URL: for public pages, use a key set to "signed requests only".
|
|
101
|
+
"""
|
|
102
|
+
query = build_query(_merge(options, kwargs))
|
|
103
|
+
unsigned = (query + "&" if query else "") + "access_key=" + _encode(self.access_key)
|
|
104
|
+
if self.secret_key:
|
|
105
|
+
unsigned += "&signature=" + sign(self.secret_key, unsigned)
|
|
106
|
+
return self.base_url + "/take?" + unsigned
|
|
107
|
+
|
|
108
|
+
def take(self, options: Optional[Mapping[str, OptionValue]] = None, /, **kwargs: OptionValue) -> bytes:
|
|
109
|
+
"""Render and return the file's bytes. Raises ArgoshotError on failure.
|
|
110
|
+
|
|
111
|
+
GET for url captures (signed when a secret key is set); a JSON POST when html or markdown is given.
|
|
112
|
+
Options are the API's names; pass ones that are Python keywords (async) in the dict.
|
|
113
|
+
"""
|
|
114
|
+
opts = _clean(_merge(options, kwargs))
|
|
115
|
+
headers = {"X-Access-Key": self.access_key, "User-Agent": "argoshot-python/" + _VERSION}
|
|
116
|
+
if "html" in opts or "markdown" in opts:
|
|
117
|
+
headers["Content-Type"] = "application/json"
|
|
118
|
+
body = json.dumps(opts).encode("utf-8")
|
|
119
|
+
request = urllib.request.Request(self.base_url + "/take", data=body, headers=headers, method="POST")
|
|
120
|
+
else:
|
|
121
|
+
query = build_query(opts)
|
|
122
|
+
if self.secret_key:
|
|
123
|
+
query += "&signature=" + sign(self.secret_key, query)
|
|
124
|
+
request = urllib.request.Request(self.base_url + "/take?" + query, headers=headers, method="GET")
|
|
125
|
+
return self._send(request)
|
|
126
|
+
|
|
127
|
+
def usage(self) -> Dict[str, Any]:
|
|
128
|
+
"""GET /usage: renders total, available and used, and the plan's limits. Costs nothing."""
|
|
129
|
+
headers = {"X-Access-Key": self.access_key, "User-Agent": "argoshot-python/" + _VERSION}
|
|
130
|
+
request = urllib.request.Request(self.base_url + "/usage", headers=headers, method="GET")
|
|
131
|
+
return json.loads(self._send(request).decode("utf-8"))
|
|
132
|
+
|
|
133
|
+
def _send(self, request: urllib.request.Request) -> bytes:
|
|
134
|
+
try:
|
|
135
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
136
|
+
return response.read()
|
|
137
|
+
except urllib.error.HTTPError as e:
|
|
138
|
+
body = e.read().decode("utf-8", errors="replace")
|
|
139
|
+
raise parse_error(e.code, body, e.headers.get("Retry-After") if e.headers else None) from None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def parse_error(status: int, body: str, retry_after: Optional[str] = None) -> ArgoshotError:
|
|
143
|
+
"""An ArgoshotError from an error response's status and body."""
|
|
144
|
+
retry: Optional[int] = None
|
|
145
|
+
if retry_after and str(retry_after).strip().isdigit():
|
|
146
|
+
retry = int(retry_after)
|
|
147
|
+
try:
|
|
148
|
+
data = json.loads(body)
|
|
149
|
+
except (ValueError, TypeError):
|
|
150
|
+
data = None
|
|
151
|
+
if isinstance(data, dict) and isinstance(data.get("error_code"), str):
|
|
152
|
+
return ArgoshotError(
|
|
153
|
+
code=data["error_code"],
|
|
154
|
+
message=data.get("error_message") or data["error_code"],
|
|
155
|
+
status=status,
|
|
156
|
+
documentation_url=data.get("documentation_url"),
|
|
157
|
+
upgrade_url=data.get("upgrade_url"),
|
|
158
|
+
returned_status_code=data.get("returned_status_code"),
|
|
159
|
+
matched_string=data.get("matched_string"),
|
|
160
|
+
retry_after=retry,
|
|
161
|
+
body=body,
|
|
162
|
+
)
|
|
163
|
+
snippet = (body or "")[:200]
|
|
164
|
+
return ArgoshotError("http_error", f"HTTP {status}" + (f": {snippet}" if snippet else ""), status, retry_after=retry, body=body)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def build_query(options: Optional[Mapping[str, OptionValue]]) -> str:
|
|
168
|
+
"""The query string of these options: names sorted, lists repeated, None left out (no access key)."""
|
|
169
|
+
opts = _clean(options)
|
|
170
|
+
parts = []
|
|
171
|
+
for name in sorted(opts):
|
|
172
|
+
value = opts[name]
|
|
173
|
+
values = value if isinstance(value, (list, tuple)) else [value]
|
|
174
|
+
for v in values:
|
|
175
|
+
if v is None:
|
|
176
|
+
continue
|
|
177
|
+
parts.append(_encode(name) + "=" + _encode(_text(v)))
|
|
178
|
+
return "&".join(parts)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def sign(secret_key: str, query: str) -> str:
|
|
182
|
+
"""The signature the API checks: lowercase hex HMAC-SHA256 of the query string, under the secret key."""
|
|
183
|
+
return hmac.new(secret_key.encode("utf-8"), query.encode("utf-8"), hashlib.sha256).hexdigest()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _merge(options: Optional[Mapping[str, OptionValue]], kwargs: Mapping[str, OptionValue]) -> Dict[str, OptionValue]:
|
|
187
|
+
merged: Dict[str, OptionValue] = dict(options or {})
|
|
188
|
+
merged.update(kwargs)
|
|
189
|
+
return merged
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _clean(options: Optional[Mapping[str, OptionValue]]) -> Dict[str, OptionValue]:
|
|
193
|
+
return {k: v for k, v in (options or {}).items() if v is not None and k not in _CLIENT_OWN}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _text(v: Any) -> str:
|
|
197
|
+
if isinstance(v, bool):
|
|
198
|
+
return "true" if v else "false"
|
|
199
|
+
return str(v)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _encode(s: str) -> str:
|
|
203
|
+
# RFC 3986: everything but A-Z a-z 0-9 - . _ ~ is percent-encoded (a space is %20, a + is %2B).
|
|
204
|
+
return urllib.parse.quote(s, safe="-._~")
|
argoshot/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: argoshot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official client for the Argoshot screenshot API: screenshots, PDFs and signed og:image URLs of any web page or HTML.
|
|
5
|
+
Project-URL: Homepage, https://argoshot.com
|
|
6
|
+
Project-URL: Documentation, https://argoshot.com/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/rrlabs-io/argoshot-python
|
|
8
|
+
Author: Argoshot
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: argoshot,html-to-image,og-image,pdf,screenshot,screenshot-api
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
17
|
+
Classifier: Topic :: Multimedia :: Graphics :: Capture :: Screen Capture
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# argoshot
|
|
23
|
+
|
|
24
|
+
The official Python client for [Argoshot](https://argoshot.com), the screenshot API: screenshots, PDFs and signed
|
|
25
|
+
`og:image` URLs of any web page or HTML. **Free to start.** Docs: https://argoshot.com/docs
|
|
26
|
+
|
|
27
|
+
Standard library only (no dependencies), Python 3.8+, typed.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
pip install argoshot
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Get your access key (and secret key, for signed URLs) from the dashboard's API keys page.
|
|
36
|
+
|
|
37
|
+
## Screenshot to a file
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import os
|
|
41
|
+
from argoshot import Argoshot
|
|
42
|
+
|
|
43
|
+
client = Argoshot(os.environ["ARGOSHOT_ACCESS_KEY"])
|
|
44
|
+
|
|
45
|
+
png = client.take(url="https://example.com", format="png", full_page=True, block_cookie_banners=True)
|
|
46
|
+
with open("example.png", "wb") as f:
|
|
47
|
+
f.write(png)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Signed og:image URL
|
|
51
|
+
|
|
52
|
+
`url()` builds a `GET /take` link for `<img src>` or `<meta property="og:image">`. With a secret key it is signed
|
|
53
|
+
(HMAC-SHA256 of the query string), so nobody can change its options. Set the key to **signed requests only** in the
|
|
54
|
+
dashboard before you put its links in public pages.
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
client = Argoshot(os.environ["ARGOSHOT_ACCESS_KEY"], secret_key=os.environ["ARGOSHOT_SECRET_KEY"])
|
|
58
|
+
|
|
59
|
+
og_image = client.url(
|
|
60
|
+
url="https://example.com/blog/my-post",
|
|
61
|
+
viewport_width=1200,
|
|
62
|
+
viewport_height=630,
|
|
63
|
+
format="png",
|
|
64
|
+
cache=True,
|
|
65
|
+
cache_ttl=86400,
|
|
66
|
+
)
|
|
67
|
+
# <meta property="og:image" content="{{ og_image }}">
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## HTML to PNG
|
|
71
|
+
|
|
72
|
+
When `html` (or `markdown`) is given, `take()` sends a JSON `POST` instead of a long query string.
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
card = client.take(
|
|
76
|
+
html='<div style="font: 64px system-ui; padding: 80px">Hello from Argoshot</div>',
|
|
77
|
+
format="png",
|
|
78
|
+
viewport_width=1200,
|
|
79
|
+
viewport_height=630,
|
|
80
|
+
)
|
|
81
|
+
with open("card.png", "wb") as f:
|
|
82
|
+
f.write(card)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Options
|
|
86
|
+
|
|
87
|
+
Options are the API's own names (https://argoshot.com/docs/options), as keyword arguments or a dict; lists are lists:
|
|
88
|
+
`hide_selectors=[".banner", "#chat"]`. Pass names that are Python keywords in the dict:
|
|
89
|
+
`client.take({"url": "https://example.com", "async": True, "webhook_url": "https://you.example/hook"})`.
|
|
90
|
+
`argoshot.TakeOptions` types the common ones.
|
|
91
|
+
|
|
92
|
+
## Errors
|
|
93
|
+
|
|
94
|
+
A failed request raises `ArgoshotError` with the API's `code` (e.g. `selector_not_found`, `screenshots_limit_reached`),
|
|
95
|
+
`message`, HTTP `status`, `documentation_url`, and `upgrade_url` / `retry_after` when the API gives them.
|
|
96
|
+
All codes: https://argoshot.com/docs/errors
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from argoshot import ArgoshotError
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
client.take(url="https://example.com", selector="#missing", error_on_selector_not_found=True)
|
|
103
|
+
except ArgoshotError as e:
|
|
104
|
+
print(e.code, e.message)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Usage
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
print(client.usage()) # {"total": ..., "available": ..., "used": ..., ...}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Configuration
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
Argoshot(access_key, secret_key=None, base_url="https://api.argoshot.com", timeout=120.0)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Note: a key set to *signed requests only* cannot send JSON `POST` requests (the API refuses them), so
|
|
120
|
+
`take(html=...)` needs a key that permits unsigned requests.
|
|
121
|
+
|
|
122
|
+
## Licence
|
|
123
|
+
|
|
124
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
argoshot/__init__.py,sha256=AOMF04Zfs-C0r0xmYGmyuQKdvW_-OuaK5ICC19_B4Pk,444
|
|
2
|
+
argoshot/_client.py,sha256=GEorMR5fK9hpAmiyRZEcXMnULbW46r7GFo04bgJ-QjE,7879
|
|
3
|
+
argoshot/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
argoshot-0.1.0.dist-info/METADATA,sha256=04rfrZG4O5tZ2mzghMhvJMa7971KF2r35PRAJBx-Sjo,3853
|
|
5
|
+
argoshot-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
argoshot-0.1.0.dist-info/licenses/LICENSE,sha256=zGqNaaOCF1uU2FOpGgUM-1DtUwpcg48Sllk1SZJ-C5M,1063
|
|
7
|
+
argoshot-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RRLabs
|
|
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.
|