tzafon 2.3.0__py3-none-any.whl → 2.4.4__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.
Potentially problematic release.
This version of tzafon might be problematic. Click here for more details.
- tzafon/__init__.py +10 -0
- tzafon/_client.py +38 -0
- tzafon/_utils/_utils.py +1 -1
- tzafon/_version.py +1 -1
- tzafon/lib/__init__.py +21 -0
- tzafon/lib/result_types.py +77 -0
- tzafon/lib/wrapper.py +326 -0
- tzafon-2.4.4.dist-info/METADATA +229 -0
- {tzafon-2.3.0.dist-info → tzafon-2.4.4.dist-info}/RECORD +11 -8
- tzafon-2.3.0.dist-info/METADATA +0 -429
- {tzafon-2.3.0.dist-info → tzafon-2.4.4.dist-info}/WHEEL +0 -0
- {tzafon-2.3.0.dist-info → tzafon-2.4.4.dist-info}/licenses/LICENSE +0 -0
tzafon/__init__.py
CHANGED
|
@@ -88,6 +88,16 @@ if not _t.TYPE_CHECKING:
|
|
|
88
88
|
|
|
89
89
|
_setup_logging()
|
|
90
90
|
|
|
91
|
+
# Add convenience wrapper to Computer client
|
|
92
|
+
from .lib.wrapper import ComputerSession
|
|
93
|
+
|
|
94
|
+
def _create_wrapper(self: Computer, kind: str = "browser", **kwargs) -> ComputerSession:
|
|
95
|
+
"""Create a computer and return a session wrapper with cleaner API."""
|
|
96
|
+
response = self.computers.create(kind=kind, **kwargs)
|
|
97
|
+
return ComputerSession(self, response.id)
|
|
98
|
+
|
|
99
|
+
Computer.create = _create_wrapper # type: ignore
|
|
100
|
+
|
|
91
101
|
# Update the __module__ attribute for exported symbols so that
|
|
92
102
|
# error messages point to this module instead of the module
|
|
93
103
|
# it was originally defined in, e.g.
|
tzafon/_client.py
CHANGED
|
@@ -30,6 +30,24 @@ from ._base_client import (
|
|
|
30
30
|
AsyncAPIClient,
|
|
31
31
|
)
|
|
32
32
|
|
|
33
|
+
|
|
34
|
+
def _load_env_file(filepath: str = ".env") -> None:
|
|
35
|
+
"""Load environment variables from a .env file."""
|
|
36
|
+
try:
|
|
37
|
+
with open(filepath) as f:
|
|
38
|
+
for line in f:
|
|
39
|
+
line = line.strip()
|
|
40
|
+
if line and not line.startswith("#") and "=" in line:
|
|
41
|
+
key, value = line.split("=", 1)
|
|
42
|
+
key = key.strip()
|
|
43
|
+
value = value.strip()
|
|
44
|
+
# Strip quotes if present
|
|
45
|
+
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
|
|
46
|
+
value = value[1:-1]
|
|
47
|
+
os.environ.setdefault(key, value)
|
|
48
|
+
except FileNotFoundError:
|
|
49
|
+
pass
|
|
50
|
+
|
|
33
51
|
__all__ = [
|
|
34
52
|
"Timeout",
|
|
35
53
|
"Transport",
|
|
@@ -79,6 +97,12 @@ class Computer(SyncAPIClient):
|
|
|
79
97
|
"""
|
|
80
98
|
if api_key is None:
|
|
81
99
|
api_key = os.environ.get("TZAFON_API_KEY")
|
|
100
|
+
|
|
101
|
+
# Try to load from .env file if still not found
|
|
102
|
+
if api_key is None:
|
|
103
|
+
_load_env_file()
|
|
104
|
+
api_key = os.environ.get("TZAFON_API_KEY")
|
|
105
|
+
|
|
82
106
|
if api_key is None:
|
|
83
107
|
raise ComputerError(
|
|
84
108
|
"The api_key client option must be set either by passing api_key to the client or by setting the TZAFON_API_KEY environment variable"
|
|
@@ -90,6 +114,10 @@ class Computer(SyncAPIClient):
|
|
|
90
114
|
if base_url is None:
|
|
91
115
|
base_url = f"https://v2.tzafon.ai/v1"
|
|
92
116
|
|
|
117
|
+
# Strip trailing slash to prevent double-slash in URLs (httpx adds it back)
|
|
118
|
+
if isinstance(base_url, str):
|
|
119
|
+
base_url = base_url.rstrip('/')
|
|
120
|
+
|
|
93
121
|
super().__init__(
|
|
94
122
|
version=__version__,
|
|
95
123
|
base_url=base_url,
|
|
@@ -247,6 +275,12 @@ class AsyncComputer(AsyncAPIClient):
|
|
|
247
275
|
"""
|
|
248
276
|
if api_key is None:
|
|
249
277
|
api_key = os.environ.get("TZAFON_API_KEY")
|
|
278
|
+
|
|
279
|
+
# Try to load from .env file if still not found
|
|
280
|
+
if api_key is None:
|
|
281
|
+
_load_env_file()
|
|
282
|
+
api_key = os.environ.get("TZAFON_API_KEY")
|
|
283
|
+
|
|
250
284
|
if api_key is None:
|
|
251
285
|
raise ComputerError(
|
|
252
286
|
"The api_key client option must be set either by passing api_key to the client or by setting the TZAFON_API_KEY environment variable"
|
|
@@ -258,6 +292,10 @@ class AsyncComputer(AsyncAPIClient):
|
|
|
258
292
|
if base_url is None:
|
|
259
293
|
base_url = f"https://v2.tzafon.ai/v1"
|
|
260
294
|
|
|
295
|
+
# Strip trailing slash to prevent double-slash in URLs (httpx adds it back)
|
|
296
|
+
if isinstance(base_url, str):
|
|
297
|
+
base_url = base_url.rstrip('/')
|
|
298
|
+
|
|
261
299
|
super().__init__(
|
|
262
300
|
version=__version__,
|
|
263
301
|
base_url=base_url,
|
tzafon/_utils/_utils.py
CHANGED
|
@@ -133,7 +133,7 @@ def is_given(obj: _T | NotGiven | Omit) -> TypeGuard[_T]:
|
|
|
133
133
|
# Type safe methods for narrowing types with TypeVars.
|
|
134
134
|
# The default narrowing for isinstance(obj, dict) is dict[unknown, unknown],
|
|
135
135
|
# however this cause Pyright to rightfully report errors. As we know we don't
|
|
136
|
-
# care about the contained types we can safely use `object` in
|
|
136
|
+
# care about the contained types we can safely use `object` in its place.
|
|
137
137
|
#
|
|
138
138
|
# There are two separate functions defined, `is_*` and `is_*_t` for different use cases.
|
|
139
139
|
# `is_*` is for when you're dealing with an unknown input
|
tzafon/_version.py
CHANGED
tzafon/lib/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Custom library extensions - safe from Stainless regeneration."""
|
|
2
|
+
|
|
3
|
+
from .wrapper import ComputerSession
|
|
4
|
+
from .result_types import (
|
|
5
|
+
ScreenshotResult,
|
|
6
|
+
HTMLResult,
|
|
7
|
+
DebugResult,
|
|
8
|
+
get_screenshot_url,
|
|
9
|
+
get_html_content,
|
|
10
|
+
get_debug_response,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"ComputerSession",
|
|
15
|
+
"ScreenshotResult",
|
|
16
|
+
"HTMLResult",
|
|
17
|
+
"DebugResult",
|
|
18
|
+
"get_screenshot_url",
|
|
19
|
+
"get_html_content",
|
|
20
|
+
"get_debug_response",
|
|
21
|
+
]
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Strongly-typed result helpers for better IntelliSense."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Optional, TypedDict
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from ..types.action_result import ActionResult
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"ScreenshotResult",
|
|
12
|
+
"HTMLResult",
|
|
13
|
+
"DebugResult",
|
|
14
|
+
"get_screenshot_url",
|
|
15
|
+
"get_html_content",
|
|
16
|
+
"get_debug_response",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ScreenshotResult(TypedDict, total=False):
|
|
21
|
+
"""Result from screenshot action containing the image URL."""
|
|
22
|
+
screenshot_url: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class HTMLResult(TypedDict, total=False):
|
|
26
|
+
"""Result from html() action containing the page HTML."""
|
|
27
|
+
html_content: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class DebugResult(TypedDict, total=False):
|
|
31
|
+
"""Result from debug command containing command output."""
|
|
32
|
+
debug_response: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_screenshot_url(result: ActionResult) -> Optional[str]:
|
|
36
|
+
"""
|
|
37
|
+
Extract screenshot URL from action result.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
result: ActionResult from screenshot() call
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
Screenshot URL if available, None otherwise
|
|
44
|
+
"""
|
|
45
|
+
if result.result:
|
|
46
|
+
return result.result.get("screenshot_url") # type: ignore
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def get_html_content(result: ActionResult) -> Optional[str]:
|
|
51
|
+
"""
|
|
52
|
+
Extract HTML content from action result.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
result: ActionResult from html() call
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
HTML content if available, None otherwise
|
|
59
|
+
"""
|
|
60
|
+
if result.result:
|
|
61
|
+
return result.result.get("html_content") # type: ignore
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def get_debug_response(result: ActionResult) -> Optional[str]:
|
|
66
|
+
"""
|
|
67
|
+
Extract debug command output from action result.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
result: ActionResult from debug() call
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
Command output if available, None otherwise
|
|
74
|
+
"""
|
|
75
|
+
if result.result:
|
|
76
|
+
return result.result.get("debug_response") # type: ignore
|
|
77
|
+
return None
|
tzafon/lib/wrapper.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""Lightweight wrapper for cleaner API - lives in lib/ to avoid Stainless regeneration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Optional
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from .._client import Computer as TzafonClient
|
|
9
|
+
from ..types.action_result import ActionResult
|
|
10
|
+
|
|
11
|
+
__all__ = ["ComputerSession"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ComputerSession:
|
|
15
|
+
"""
|
|
16
|
+
High-level session wrapper with cleaner API and context manager support.
|
|
17
|
+
|
|
18
|
+
This wraps a computer instance and provides:
|
|
19
|
+
- Automatic ID management (no need to pass computer_id to each call)
|
|
20
|
+
- Context manager support for automatic cleanup
|
|
21
|
+
- Simplified method signatures
|
|
22
|
+
- Better IntelliSense through typed helper methods
|
|
23
|
+
|
|
24
|
+
Example:
|
|
25
|
+
```python
|
|
26
|
+
from tzafon import Computer
|
|
27
|
+
|
|
28
|
+
client = Computer()
|
|
29
|
+
with client.create(kind="browser") as computer:
|
|
30
|
+
computer.navigate("https://example.com")
|
|
31
|
+
result = computer.screenshot()
|
|
32
|
+
url = computer.get_screenshot_url(result)
|
|
33
|
+
# Automatically terminates on exit
|
|
34
|
+
```
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, client: TzafonClient, computer_id: str) -> None:
|
|
38
|
+
"""
|
|
39
|
+
Initialize session wrapper.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
client: The Computer client instance
|
|
43
|
+
computer_id: The computer/session ID
|
|
44
|
+
"""
|
|
45
|
+
self._client = client
|
|
46
|
+
self.id = computer_id
|
|
47
|
+
|
|
48
|
+
def navigate(self, url: str) -> ActionResult:
|
|
49
|
+
"""
|
|
50
|
+
Navigate to a URL.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
url: The URL to navigate to (e.g., "https://example.com")
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
ActionResult with status and timestamp
|
|
57
|
+
"""
|
|
58
|
+
return self._client.computers.navigate(self.id, url=url)
|
|
59
|
+
|
|
60
|
+
def type(self, text: str) -> ActionResult:
|
|
61
|
+
"""
|
|
62
|
+
Type text into the currently focused element.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
text: The text to type
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
ActionResult with status and timestamp
|
|
69
|
+
"""
|
|
70
|
+
return self._client.computers.type_text(self.id, text=text)
|
|
71
|
+
|
|
72
|
+
def click(self, x: float, y: float) -> ActionResult:
|
|
73
|
+
"""
|
|
74
|
+
Click at specific coordinates.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
x: X coordinate (pixels from left)
|
|
78
|
+
y: Y coordinate (pixels from top)
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
ActionResult with status and timestamp
|
|
82
|
+
"""
|
|
83
|
+
return self._client.computers.click(self.id, x=x, y=y)
|
|
84
|
+
|
|
85
|
+
def screenshot(self, base64: bool = False) -> ActionResult:
|
|
86
|
+
"""
|
|
87
|
+
Capture a screenshot of the current viewport.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
base64: If True, return base64-encoded image data instead of URL
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
ActionResult with result.screenshot_url containing the image URL.
|
|
94
|
+
Use get_screenshot_url() helper to extract the URL with type safety.
|
|
95
|
+
|
|
96
|
+
Example:
|
|
97
|
+
```python
|
|
98
|
+
result = computer.screenshot()
|
|
99
|
+
url = computer.get_screenshot_url(result)
|
|
100
|
+
```
|
|
101
|
+
"""
|
|
102
|
+
return self._client.computers.capture_screenshot(self.id, base64=base64)
|
|
103
|
+
|
|
104
|
+
def double_click(self, x: float, y: float) -> ActionResult:
|
|
105
|
+
"""
|
|
106
|
+
Double-click at specific coordinates.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
x: X coordinate (pixels from left)
|
|
110
|
+
y: Y coordinate (pixels from top)
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
ActionResult with status and timestamp
|
|
114
|
+
"""
|
|
115
|
+
return self._client.computers.double_click(self.id, x=x, y=y)
|
|
116
|
+
|
|
117
|
+
def right_click(self, x: float, y: float) -> ActionResult:
|
|
118
|
+
"""
|
|
119
|
+
Right-click at specific coordinates.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
x: X coordinate (pixels from left)
|
|
123
|
+
y: Y coordinate (pixels from top)
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
ActionResult with status and timestamp
|
|
127
|
+
"""
|
|
128
|
+
return self._client.computers.right_click(self.id, x=x, y=y)
|
|
129
|
+
|
|
130
|
+
def drag(self, x1: float, y1: float, x2: float, y2: float) -> ActionResult:
|
|
131
|
+
"""
|
|
132
|
+
Perform click-and-drag from one point to another.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
x1: Starting X coordinate
|
|
136
|
+
y1: Starting Y coordinate
|
|
137
|
+
x2: Ending X coordinate
|
|
138
|
+
y2: Ending Y coordinate
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
ActionResult with status and timestamp
|
|
142
|
+
"""
|
|
143
|
+
return self._client.computers.drag(self.id, x1=x1, y1=y1, x2=x2, y2=y2)
|
|
144
|
+
|
|
145
|
+
def hotkey(self, *keys: str) -> ActionResult:
|
|
146
|
+
"""
|
|
147
|
+
Press a keyboard shortcut combination.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
*keys: Keys to press together (e.g., "Control", "c" for Ctrl+C)
|
|
151
|
+
Can be passed as separate arguments or as a single list/tuple
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
ActionResult with status and timestamp
|
|
155
|
+
|
|
156
|
+
Example:
|
|
157
|
+
```python
|
|
158
|
+
computer.hotkey("Control", "c") # Copy - varargs style
|
|
159
|
+
computer.hotkey(["Control", "v"]) # Paste - list style
|
|
160
|
+
computer.hotkey("Control", "Shift", "p") # Multiple modifiers
|
|
161
|
+
```
|
|
162
|
+
"""
|
|
163
|
+
# Handle both hotkey("a", "b") and hotkey(["a", "b"]) calling styles
|
|
164
|
+
if len(keys) == 1 and isinstance(keys[0], (list, tuple)):
|
|
165
|
+
keys_list = list(keys[0])
|
|
166
|
+
else:
|
|
167
|
+
keys_list = list(keys)
|
|
168
|
+
|
|
169
|
+
return self._client.computers.execute_action(self.id, action={"type": "keypress", "keys": keys_list})
|
|
170
|
+
|
|
171
|
+
def scroll(self, dx: float = 0, dy: float = 0) -> ActionResult:
|
|
172
|
+
"""
|
|
173
|
+
Scroll the viewport.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
dx: Horizontal scroll delta (positive = right, negative = left)
|
|
177
|
+
dy: Vertical scroll delta (positive = down, negative = up)
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
ActionResult with status and timestamp
|
|
181
|
+
"""
|
|
182
|
+
return self._client.computers.scroll_viewport(self.id, dx=dx, dy=dy)
|
|
183
|
+
|
|
184
|
+
def wait(self, seconds: float) -> ActionResult:
|
|
185
|
+
"""
|
|
186
|
+
Wait for a specified number of seconds on the remote computer.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
seconds: Number of seconds to wait (can be fractional, e.g., 0.5 for half a second)
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
ActionResult with status and timestamp
|
|
193
|
+
|
|
194
|
+
Example:
|
|
195
|
+
```python
|
|
196
|
+
result = computer.wait(1) # Wait 1 second
|
|
197
|
+
result = computer.wait(0.5) # Wait 500 milliseconds
|
|
198
|
+
result = computer.wait(2.5) # Wait 2.5 seconds
|
|
199
|
+
```
|
|
200
|
+
"""
|
|
201
|
+
ms = int(seconds * 1000)
|
|
202
|
+
return self._client.computers.execute_action(self.id, action={"type": "wait", "ms": ms})
|
|
203
|
+
|
|
204
|
+
def html(self, auto_detect_encoding: bool = False) -> ActionResult:
|
|
205
|
+
"""
|
|
206
|
+
Get the HTML content of the current page.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
auto_detect_encoding: Automatically detect and handle character encoding
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
ActionResult with result.html_content containing the page HTML.
|
|
213
|
+
Use get_html_content() helper to extract the HTML with type safety.
|
|
214
|
+
|
|
215
|
+
Example:
|
|
216
|
+
```python
|
|
217
|
+
result = computer.html()
|
|
218
|
+
html = computer.get_html_content(result)
|
|
219
|
+
```
|
|
220
|
+
"""
|
|
221
|
+
return self._client.computers.get_html(self.id, auto_detect_encoding=auto_detect_encoding)
|
|
222
|
+
|
|
223
|
+
def debug(self, command: str, timeout_seconds: int = 120, max_output_length: int = 65536) -> ActionResult:
|
|
224
|
+
"""
|
|
225
|
+
Execute a shell command inside the session.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
command: Shell command to execute
|
|
229
|
+
timeout_seconds: Command timeout in seconds (default: 120)
|
|
230
|
+
max_output_length: Maximum output length in bytes (default: 65536)
|
|
231
|
+
|
|
232
|
+
Returns:
|
|
233
|
+
ActionResult with result.debug_response containing command output.
|
|
234
|
+
Use get_debug_response() helper to extract output with type safety.
|
|
235
|
+
|
|
236
|
+
Example:
|
|
237
|
+
```python
|
|
238
|
+
result = computer.debug("ls -la")
|
|
239
|
+
output = computer.get_debug_response(result)
|
|
240
|
+
```
|
|
241
|
+
"""
|
|
242
|
+
return self._client.computers.debug(
|
|
243
|
+
self.id,
|
|
244
|
+
command=command,
|
|
245
|
+
timeout_seconds=timeout_seconds,
|
|
246
|
+
max_output_length=max_output_length
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
def set_viewport(self, width: int, height: int, scale_factor: float = 1.0) -> ActionResult:
|
|
250
|
+
"""
|
|
251
|
+
Change the browser viewport dimensions.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
width: Viewport width in pixels
|
|
255
|
+
height: Viewport height in pixels
|
|
256
|
+
scale_factor: Device pixel ratio / zoom level (default: 1.0)
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
ActionResult with status and timestamp
|
|
260
|
+
"""
|
|
261
|
+
return self._client.computers.set_viewport(
|
|
262
|
+
self.id,
|
|
263
|
+
width=width,
|
|
264
|
+
height=height,
|
|
265
|
+
scale_factor=scale_factor
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
# Typed helper methods for extracting results
|
|
269
|
+
|
|
270
|
+
def get_screenshot_url(self, result: ActionResult) -> Optional[str]:
|
|
271
|
+
"""
|
|
272
|
+
Extract screenshot URL from action result with type safety.
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
result: ActionResult from screenshot() call
|
|
276
|
+
|
|
277
|
+
Returns:
|
|
278
|
+
Screenshot URL if available, None otherwise
|
|
279
|
+
"""
|
|
280
|
+
if result.result:
|
|
281
|
+
return result.result.get("screenshot_url") # type: ignore
|
|
282
|
+
return None
|
|
283
|
+
|
|
284
|
+
def get_html_content(self, result: ActionResult) -> Optional[str]:
|
|
285
|
+
"""
|
|
286
|
+
Extract HTML content from action result with type safety.
|
|
287
|
+
|
|
288
|
+
Args:
|
|
289
|
+
result: ActionResult from html() call
|
|
290
|
+
|
|
291
|
+
Returns:
|
|
292
|
+
HTML content if available, None otherwise
|
|
293
|
+
"""
|
|
294
|
+
if result.result:
|
|
295
|
+
return result.result.get("html_content") # type: ignore
|
|
296
|
+
return None
|
|
297
|
+
|
|
298
|
+
def get_debug_response(self, result: ActionResult) -> Optional[str]:
|
|
299
|
+
"""
|
|
300
|
+
Extract debug command output from action result with type safety.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
result: ActionResult from debug() call
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
Command output if available, None otherwise
|
|
307
|
+
"""
|
|
308
|
+
if result.result:
|
|
309
|
+
return result.result.get("debug_response") # type: ignore
|
|
310
|
+
return None
|
|
311
|
+
|
|
312
|
+
def terminate(self) -> None:
|
|
313
|
+
"""
|
|
314
|
+
Terminate the computer session and clean up resources.
|
|
315
|
+
|
|
316
|
+
Note: When using the context manager (with statement), this is called automatically.
|
|
317
|
+
"""
|
|
318
|
+
self._client.computers.terminate(self.id)
|
|
319
|
+
|
|
320
|
+
def __enter__(self) -> ComputerSession:
|
|
321
|
+
"""Context manager entry - returns self for use in with statement."""
|
|
322
|
+
return self
|
|
323
|
+
|
|
324
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
325
|
+
"""Context manager exit - automatically terminates the session."""
|
|
326
|
+
self.terminate()
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: tzafon
|
|
3
|
+
Version: 2.4.4
|
|
4
|
+
Summary: The official Python library for the computer API
|
|
5
|
+
Project-URL: Homepage, https://github.com/tzafon/computer-python
|
|
6
|
+
Project-URL: Repository, https://github.com/tzafon/computer-python
|
|
7
|
+
Author-email: Computer <atul.gavande@tzafon.ai>
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: MacOS
|
|
12
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Operating System :: POSIX
|
|
15
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.8
|
|
25
|
+
Requires-Dist: anyio<5,>=3.5.0
|
|
26
|
+
Requires-Dist: distro<2,>=1.7.0
|
|
27
|
+
Requires-Dist: httpx<1,>=0.23.0
|
|
28
|
+
Requires-Dist: pydantic<3,>=1.9.0
|
|
29
|
+
Requires-Dist: sniffio
|
|
30
|
+
Requires-Dist: typing-extensions<5,>=4.10
|
|
31
|
+
Provides-Extra: aiohttp
|
|
32
|
+
Requires-Dist: aiohttp; extra == 'aiohttp'
|
|
33
|
+
Requires-Dist: httpx-aiohttp>=0.1.9; extra == 'aiohttp'
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
|
|
36
|
+
# Tzafon Python SDK
|
|
37
|
+
|
|
38
|
+
[](https://pypi.org/project/tzafon/)
|
|
39
|
+
|
|
40
|
+
Remote browser and desktop automation. Control browsers and desktops programmatically through a simple Python API.
|
|
41
|
+
|
|
42
|
+
## Installation
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install tzafon
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Quick Start
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from tzafon import Computer
|
|
52
|
+
|
|
53
|
+
client = Computer() # Reads TZAFON_API_KEY from environment
|
|
54
|
+
|
|
55
|
+
# Create and control a browser instance
|
|
56
|
+
with client.create(kind="browser") as computer:
|
|
57
|
+
computer.navigate("https://wikipedia.com")
|
|
58
|
+
|
|
59
|
+
result = computer.screenshot()
|
|
60
|
+
url = computer.get_screenshot_url(result)
|
|
61
|
+
print(f"Screenshot: {url}")
|
|
62
|
+
|
|
63
|
+
computer.click(100, 200)
|
|
64
|
+
computer.type("Hello, world!")
|
|
65
|
+
|
|
66
|
+
# Automatically terminates when exiting context
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Set your API key:
|
|
70
|
+
```bash
|
|
71
|
+
export TZAFON_API_KEY="your-api-key"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Or use a `.env` file with [python-dotenv](https://pypi.org/project/python-dotenv/).
|
|
75
|
+
|
|
76
|
+
## Features
|
|
77
|
+
|
|
78
|
+
**Session Management**
|
|
79
|
+
- Context manager support for automatic cleanup
|
|
80
|
+
- Manual session control when needed
|
|
81
|
+
- Browser, desktop, and code environments
|
|
82
|
+
|
|
83
|
+
**Browser Actions**
|
|
84
|
+
- Navigation: `navigate(url)`
|
|
85
|
+
- Mouse: `click()`, `double_click()`, `right_click()`, `drag()`
|
|
86
|
+
- Keyboard: `type()`, `hotkey()`
|
|
87
|
+
- Viewport: `scroll()`, `set_viewport()`
|
|
88
|
+
- Capture: `screenshot()`, `html()`
|
|
89
|
+
- Debug: Execute shell commands with `debug()`
|
|
90
|
+
|
|
91
|
+
**Type Safety**
|
|
92
|
+
- Full type annotations for IDE autocomplete
|
|
93
|
+
- Pydantic models for responses
|
|
94
|
+
- TypedDict for request parameters
|
|
95
|
+
- Helper methods for result extraction
|
|
96
|
+
|
|
97
|
+
## Examples
|
|
98
|
+
|
|
99
|
+
### Browser Automation
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
with client.create(kind="browser") as computer:
|
|
103
|
+
# Navigate and interact
|
|
104
|
+
computer.navigate("https://github.com/login")
|
|
105
|
+
computer.click(300, 400)
|
|
106
|
+
computer.type("username")
|
|
107
|
+
computer.hotkey("Control", "a") # Select all
|
|
108
|
+
|
|
109
|
+
# Capture state
|
|
110
|
+
html_result = computer.html()
|
|
111
|
+
html = computer.get_html_content(html_result)
|
|
112
|
+
|
|
113
|
+
# Execute commands
|
|
114
|
+
debug_result = computer.debug("ls -la")
|
|
115
|
+
output = computer.get_debug_response(debug_result)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### Manual Session Management
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
computer = client.create(kind="browser")
|
|
122
|
+
try:
|
|
123
|
+
computer.navigate("https://example.com")
|
|
124
|
+
screenshot = computer.screenshot()
|
|
125
|
+
finally:
|
|
126
|
+
computer.terminate()
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Async Support
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from tzafon import AsyncComputer
|
|
133
|
+
|
|
134
|
+
async with AsyncComputer() as client:
|
|
135
|
+
computer = await client.computers.create(kind="browser")
|
|
136
|
+
await client.computers.navigate(computer.id, url="https://example.com")
|
|
137
|
+
await client.computers.terminate(computer.id)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Advanced Usage
|
|
141
|
+
|
|
142
|
+
### Raw SDK Access
|
|
143
|
+
|
|
144
|
+
The simplified wrapper uses the generated SDK under the hood. You can access it directly:
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
# Low-level API
|
|
148
|
+
response = client.computers.create(kind="browser")
|
|
149
|
+
client.computers.navigate(response.id, url="https://example.com")
|
|
150
|
+
result = client.computers.capture_screenshot(response.id)
|
|
151
|
+
client.computers.terminate(response.id)
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### Error Handling
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
import tzafon
|
|
158
|
+
|
|
159
|
+
try:
|
|
160
|
+
with client.create(kind="browser") as computer:
|
|
161
|
+
computer.navigate("https://example.com")
|
|
162
|
+
except tzafon.RateLimitError:
|
|
163
|
+
print("Rate limit exceeded, back off")
|
|
164
|
+
except tzafon.AuthenticationError:
|
|
165
|
+
print("Invalid API key")
|
|
166
|
+
except tzafon.APIError as e:
|
|
167
|
+
print(f"API error: {e}")
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### Configuration
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
from tzafon import Computer
|
|
174
|
+
|
|
175
|
+
client = Computer(
|
|
176
|
+
api_key="your-api-key", # Or use TZAFON_API_KEY env var
|
|
177
|
+
base_url="https://...", # Optional: custom endpoint
|
|
178
|
+
timeout=120.0, # Request timeout in seconds
|
|
179
|
+
max_retries=2, # Retry failed requests
|
|
180
|
+
)
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## API Reference
|
|
184
|
+
|
|
185
|
+
**Session Methods**
|
|
186
|
+
- `navigate(url)` - Navigate to URL
|
|
187
|
+
- `click(x, y)` - Click at coordinates
|
|
188
|
+
- `double_click(x, y)` - Double-click
|
|
189
|
+
- `right_click(x, y)` - Right-click
|
|
190
|
+
- `drag(x1, y1, x2, y2)` - Click and drag
|
|
191
|
+
- `type(text)` - Type text
|
|
192
|
+
- `hotkey(*keys)` - Press key combination
|
|
193
|
+
- `scroll(dx, dy)` - Scroll viewport
|
|
194
|
+
- `screenshot(base64=False)` - Capture screenshot
|
|
195
|
+
- `html(auto_detect_encoding=False)` - Get page HTML
|
|
196
|
+
- `debug(command, timeout_seconds=120, max_output_length=65536)` - Run shell command
|
|
197
|
+
- `set_viewport(width, height, scale_factor=1.0)` - Set viewport size
|
|
198
|
+
- `terminate()` - End session
|
|
199
|
+
|
|
200
|
+
**Helper Methods**
|
|
201
|
+
- `get_screenshot_url(result)` - Extract screenshot URL from result
|
|
202
|
+
- `get_html_content(result)` - Extract HTML from result
|
|
203
|
+
- `get_debug_response(result)` - Extract command output from result
|
|
204
|
+
|
|
205
|
+
## Error Codes
|
|
206
|
+
|
|
207
|
+
| Status | Error Type |
|
|
208
|
+
|--------|------------|
|
|
209
|
+
| 400 | `BadRequestError` |
|
|
210
|
+
| 401 | `AuthenticationError` |
|
|
211
|
+
| 403 | `PermissionDeniedError` |
|
|
212
|
+
| 404 | `NotFoundError` |
|
|
213
|
+
| 422 | `UnprocessableEntityError` |
|
|
214
|
+
| 429 | `RateLimitError` |
|
|
215
|
+
| ≥500 | `InternalServerError` |
|
|
216
|
+
|
|
217
|
+
## Documentation
|
|
218
|
+
|
|
219
|
+
- REST API: [docs.tzafon.ai](https://docs.tzafon.ai)
|
|
220
|
+
- Full API Reference: [api.md](https://github.com/tzafon/computer-python/tree/main/api.md)
|
|
221
|
+
- Contributing: [CONTRIBUTING.md](https://github.com/tzafon/computer-python/tree/main/CONTRIBUTING.md)
|
|
222
|
+
|
|
223
|
+
## Requirements
|
|
224
|
+
|
|
225
|
+
Python 3.8+
|
|
226
|
+
|
|
227
|
+
## License
|
|
228
|
+
|
|
229
|
+
See [LICENSE](https://github.com/tzafon/computer-python/tree/main/LICENSE)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
tzafon/__init__.py,sha256=
|
|
1
|
+
tzafon/__init__.py,sha256=BsYQQO5iiBjiYdu7iJmKOVYBD1Pf26Uv8mSxboHHvno,3084
|
|
2
2
|
tzafon/_base_client.py,sha256=5AX9s8UF-0wXUI15A1uiRcWhTNk_I4UBpt0Q-2r0aLU,67047
|
|
3
|
-
tzafon/_client.py,sha256
|
|
3
|
+
tzafon/_client.py,sha256=-WF1JpGVJvtf7Bq-CyhGYgcybdZcCptHCjGrFcYZd-s,16437
|
|
4
4
|
tzafon/_compat.py,sha256=DQBVORjFb33zch24jzkhM14msvnzY7mmSmgDLaVFUM8,6562
|
|
5
5
|
tzafon/_constants.py,sha256=S14PFzyN9-I31wiV7SmIlL5Ga0MLHxdvegInGdXH7tM,462
|
|
6
6
|
tzafon/_exceptions.py,sha256=qi7R0qNzTGtKBt4fWynaQkMnUk3YGrIp01jis82aEdo,3224
|
|
@@ -11,7 +11,7 @@ tzafon/_resource.py,sha256=EseuwN0R4kKBVcQnyF4NgCeRtc6-OrR8yWVI5fOYGHM,1112
|
|
|
11
11
|
tzafon/_response.py,sha256=Gaq-HHLZ76rKv515pCAMkfW4rbz_ManOH-7R640hrDE,28792
|
|
12
12
|
tzafon/_streaming.py,sha256=HIbrsW_WdZZmR-vQP1ZJUHFluu4t90Zx0xa7y055CBo,10157
|
|
13
13
|
tzafon/_types.py,sha256=1kStHPi-XwmomGBE0xKVtz0mdRF4Svxb8NWZR4FaSiY,7236
|
|
14
|
-
tzafon/_version.py,sha256=
|
|
14
|
+
tzafon/_version.py,sha256=XYHrS43oOJ5nnsnKv8aEguNPFhQDHewxA_3JB03X5Ro,158
|
|
15
15
|
tzafon/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
16
|
tzafon/_utils/__init__.py,sha256=7fch0GT9zpNnErbciSpUNa-SjTxxjY6kxHxKMOM4AGs,2305
|
|
17
17
|
tzafon/_utils/_compat.py,sha256=D8gtAvjJQrDWt9upS0XaG9Rr5l1QhiAx_I_1utT_tt0,1195
|
|
@@ -24,8 +24,11 @@ tzafon/_utils/_streams.py,sha256=SMC90diFFecpEg_zgDRVbdR3hSEIgVVij4taD-noMLM,289
|
|
|
24
24
|
tzafon/_utils/_sync.py,sha256=TpGLrrhRNWTJtODNE6Fup3_k7zrWm1j2RlirzBwre-0,2862
|
|
25
25
|
tzafon/_utils/_transform.py,sha256=NjCzmnfqYrsAikUHQig6N9QfuTVbKipuP3ur9mcNF-E,15951
|
|
26
26
|
tzafon/_utils/_typing.py,sha256=N_5PPuFNsaygbtA_npZd98SVN1LQQvFTKL6bkWPBZGU,4786
|
|
27
|
-
tzafon/_utils/_utils.py,sha256=
|
|
27
|
+
tzafon/_utils/_utils.py,sha256=ugfUaneOK7I8h9b3656flwf5u_kthY0gvNuqvgOLoSU,12252
|
|
28
28
|
tzafon/lib/.keep,sha256=wuNrz-5SXo3jJaJOJgz4vFHM41YH_g20F5cRQo0vLes,224
|
|
29
|
+
tzafon/lib/__init__.py,sha256=oIdVqWy0xUeoptWR5w-Y7gjJwV3uFsMUZQu7zRVTK6Y,436
|
|
30
|
+
tzafon/lib/result_types.py,sha256=_iFGJ0dlwGDoVlWDwHJ3tHAhGQ-ZUtjpqywdVKx3Aws,1847
|
|
31
|
+
tzafon/lib/wrapper.py,sha256=6b7fahveBAwyNtmOOFReIQ-_T8Tfn24zGC9AoTcTbRQ,10439
|
|
29
32
|
tzafon/resources/__init__.py,sha256=2tbxQpPYxwl6BYAmWlSblYFfmeBEasXs9oxh3vXRG2M,591
|
|
30
33
|
tzafon/resources/computers.py,sha256=mkRSD6pY8hCnks5_sTRHqL7cbbH3btM2C_z6wOlBz1E,79164
|
|
31
34
|
tzafon/types/__init__.py,sha256=_WD0kMVrCQlZgEf3UgjzF2xkxsDZ-lT_58zjcVjXYAc,1912
|
|
@@ -49,7 +52,7 @@ tzafon/types/computer_right_click_params.py,sha256=Vv5iIcyA67C9q4G5RSSW4-KVY1Vjt
|
|
|
49
52
|
tzafon/types/computer_scroll_viewport_params.py,sha256=MViBOU4FBhhaFVJ-IKcjjvm0iw3Mdv31muhWZb5Nevc,326
|
|
50
53
|
tzafon/types/computer_set_viewport_params.py,sha256=Y54APyVdHCvFs0ppNnMfYSurG-zvD_cA-RPZO0fk4_c,320
|
|
51
54
|
tzafon/types/computer_type_text_params.py,sha256=NtfxVoCF6GJhCeUWlyyCFf2XAowAKjZQAtlXntlSTIk,271
|
|
52
|
-
tzafon-2.
|
|
53
|
-
tzafon-2.
|
|
54
|
-
tzafon-2.
|
|
55
|
-
tzafon-2.
|
|
55
|
+
tzafon-2.4.4.dist-info/METADATA,sha256=YHZBZ09wEzP0GBGZkkZO-zYer9vkAnEcsdRJFz2snBI,6516
|
|
56
|
+
tzafon-2.4.4.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
|
|
57
|
+
tzafon-2.4.4.dist-info/licenses/LICENSE,sha256=ciLXi9zfEehb4Tnhy-M9I2WSRUpZjx-FK1TEChVqlDo,1048
|
|
58
|
+
tzafon-2.4.4.dist-info/RECORD,,
|
tzafon-2.3.0.dist-info/METADATA
DELETED
|
@@ -1,429 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.3
|
|
2
|
-
Name: tzafon
|
|
3
|
-
Version: 2.3.0
|
|
4
|
-
Summary: The official Python library for the computer API
|
|
5
|
-
Project-URL: Homepage, https://github.com/tzafon/computer-python
|
|
6
|
-
Project-URL: Repository, https://github.com/tzafon/computer-python
|
|
7
|
-
Author-email: Computer <atul.gavande@tzafon.ai>
|
|
8
|
-
License: MIT
|
|
9
|
-
Classifier: Intended Audience :: Developers
|
|
10
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
-
Classifier: Operating System :: MacOS
|
|
12
|
-
Classifier: Operating System :: Microsoft :: Windows
|
|
13
|
-
Classifier: Operating System :: OS Independent
|
|
14
|
-
Classifier: Operating System :: POSIX
|
|
15
|
-
Classifier: Operating System :: POSIX :: Linux
|
|
16
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
-
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
-
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
-
Classifier: Typing :: Typed
|
|
24
|
-
Requires-Python: >=3.8
|
|
25
|
-
Requires-Dist: anyio<5,>=3.5.0
|
|
26
|
-
Requires-Dist: distro<2,>=1.7.0
|
|
27
|
-
Requires-Dist: httpx<1,>=0.23.0
|
|
28
|
-
Requires-Dist: pydantic<3,>=1.9.0
|
|
29
|
-
Requires-Dist: sniffio
|
|
30
|
-
Requires-Dist: typing-extensions<5,>=4.10
|
|
31
|
-
Provides-Extra: aiohttp
|
|
32
|
-
Requires-Dist: aiohttp; extra == 'aiohttp'
|
|
33
|
-
Requires-Dist: httpx-aiohttp>=0.1.9; extra == 'aiohttp'
|
|
34
|
-
Description-Content-Type: text/markdown
|
|
35
|
-
|
|
36
|
-
# Computer Python API library
|
|
37
|
-
|
|
38
|
-
<!-- prettier-ignore -->
|
|
39
|
-
[)](https://pypi.org/project/tzafon/)
|
|
40
|
-
|
|
41
|
-
The Computer Python library provides convenient access to the Computer REST API from any Python 3.8+
|
|
42
|
-
application. The library includes type definitions for all request params and response fields,
|
|
43
|
-
and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).
|
|
44
|
-
|
|
45
|
-
It is generated with [Stainless](https://www.stainless.com/).
|
|
46
|
-
|
|
47
|
-
## Documentation
|
|
48
|
-
|
|
49
|
-
The REST API documentation can be found on [docs.tzafon.ai](http://docs.tzafon.ai). The full API of this library can be found in [api.md](https://github.com/tzafon/computer-python/tree/main/api.md).
|
|
50
|
-
|
|
51
|
-
## Installation
|
|
52
|
-
|
|
53
|
-
```sh
|
|
54
|
-
# install from PyPI
|
|
55
|
-
pip install tzafon
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
## Usage
|
|
59
|
-
|
|
60
|
-
The full API of this library can be found in [api.md](https://github.com/tzafon/computer-python/tree/main/api.md).
|
|
61
|
-
|
|
62
|
-
```python
|
|
63
|
-
import os
|
|
64
|
-
from tzafon import Computer
|
|
65
|
-
|
|
66
|
-
client = Computer(
|
|
67
|
-
api_key=os.environ.get("TZAFON_API_KEY"), # This is the default and can be omitted
|
|
68
|
-
)
|
|
69
|
-
|
|
70
|
-
computer_response = client.computers.create(
|
|
71
|
-
kind="browser",
|
|
72
|
-
)
|
|
73
|
-
print(computer_response.id)
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
While you can provide an `api_key` keyword argument,
|
|
77
|
-
we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)
|
|
78
|
-
to add `TZAFON_API_KEY="My API Key"` to your `.env` file
|
|
79
|
-
so that your API Key is not stored in source control.
|
|
80
|
-
|
|
81
|
-
## Async usage
|
|
82
|
-
|
|
83
|
-
Simply import `AsyncComputer` instead of `Computer` and use `await` with each API call:
|
|
84
|
-
|
|
85
|
-
```python
|
|
86
|
-
import os
|
|
87
|
-
import asyncio
|
|
88
|
-
from tzafon import AsyncComputer
|
|
89
|
-
|
|
90
|
-
client = AsyncComputer(
|
|
91
|
-
api_key=os.environ.get("TZAFON_API_KEY"), # This is the default and can be omitted
|
|
92
|
-
)
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
async def main() -> None:
|
|
96
|
-
computer_response = await client.computers.create(
|
|
97
|
-
kind="browser",
|
|
98
|
-
)
|
|
99
|
-
print(computer_response.id)
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
asyncio.run(main())
|
|
103
|
-
```
|
|
104
|
-
|
|
105
|
-
Functionality between the synchronous and asynchronous clients is otherwise identical.
|
|
106
|
-
|
|
107
|
-
### With aiohttp
|
|
108
|
-
|
|
109
|
-
By default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend.
|
|
110
|
-
|
|
111
|
-
You can enable this by installing `aiohttp`:
|
|
112
|
-
|
|
113
|
-
```sh
|
|
114
|
-
# install from PyPI
|
|
115
|
-
pip install tzafon[aiohttp]
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`:
|
|
119
|
-
|
|
120
|
-
```python
|
|
121
|
-
import asyncio
|
|
122
|
-
from tzafon import DefaultAioHttpClient
|
|
123
|
-
from tzafon import AsyncComputer
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
async def main() -> None:
|
|
127
|
-
async with AsyncComputer(
|
|
128
|
-
api_key="My API Key",
|
|
129
|
-
http_client=DefaultAioHttpClient(),
|
|
130
|
-
) as client:
|
|
131
|
-
computer_response = await client.computers.create(
|
|
132
|
-
kind="browser",
|
|
133
|
-
)
|
|
134
|
-
print(computer_response.id)
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
asyncio.run(main())
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
## Using types
|
|
141
|
-
|
|
142
|
-
Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like:
|
|
143
|
-
|
|
144
|
-
- Serializing back into JSON, `model.to_json()`
|
|
145
|
-
- Converting to a dictionary, `model.to_dict()`
|
|
146
|
-
|
|
147
|
-
Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.
|
|
148
|
-
|
|
149
|
-
## Nested params
|
|
150
|
-
|
|
151
|
-
Nested parameters are dictionaries, typed using `TypedDict`, for example:
|
|
152
|
-
|
|
153
|
-
```python
|
|
154
|
-
from tzafon import Computer
|
|
155
|
-
|
|
156
|
-
client = Computer()
|
|
157
|
-
|
|
158
|
-
computer_response = client.computers.create(
|
|
159
|
-
display={},
|
|
160
|
-
)
|
|
161
|
-
print(computer_response.display)
|
|
162
|
-
```
|
|
163
|
-
|
|
164
|
-
## Handling errors
|
|
165
|
-
|
|
166
|
-
When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `tzafon.APIConnectionError` is raised.
|
|
167
|
-
|
|
168
|
-
When the API returns a non-success status code (that is, 4xx or 5xx
|
|
169
|
-
response), a subclass of `tzafon.APIStatusError` is raised, containing `status_code` and `response` properties.
|
|
170
|
-
|
|
171
|
-
All errors inherit from `tzafon.APIError`.
|
|
172
|
-
|
|
173
|
-
```python
|
|
174
|
-
import tzafon
|
|
175
|
-
from tzafon import Computer
|
|
176
|
-
|
|
177
|
-
client = Computer()
|
|
178
|
-
|
|
179
|
-
try:
|
|
180
|
-
client.computers.create(
|
|
181
|
-
kind="browser",
|
|
182
|
-
)
|
|
183
|
-
except tzafon.APIConnectionError as e:
|
|
184
|
-
print("The server could not be reached")
|
|
185
|
-
print(e.__cause__) # an underlying Exception, likely raised within httpx.
|
|
186
|
-
except tzafon.RateLimitError as e:
|
|
187
|
-
print("A 429 status code was received; we should back off a bit.")
|
|
188
|
-
except tzafon.APIStatusError as e:
|
|
189
|
-
print("Another non-200-range status code was received")
|
|
190
|
-
print(e.status_code)
|
|
191
|
-
print(e.response)
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
Error codes are as follows:
|
|
195
|
-
|
|
196
|
-
| Status Code | Error Type |
|
|
197
|
-
| ----------- | -------------------------- |
|
|
198
|
-
| 400 | `BadRequestError` |
|
|
199
|
-
| 401 | `AuthenticationError` |
|
|
200
|
-
| 403 | `PermissionDeniedError` |
|
|
201
|
-
| 404 | `NotFoundError` |
|
|
202
|
-
| 422 | `UnprocessableEntityError` |
|
|
203
|
-
| 429 | `RateLimitError` |
|
|
204
|
-
| >=500 | `InternalServerError` |
|
|
205
|
-
| N/A | `APIConnectionError` |
|
|
206
|
-
|
|
207
|
-
### Retries
|
|
208
|
-
|
|
209
|
-
Certain errors are automatically retried 2 times by default, with a short exponential backoff.
|
|
210
|
-
Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,
|
|
211
|
-
429 Rate Limit, and >=500 Internal errors are all retried by default.
|
|
212
|
-
|
|
213
|
-
You can use the `max_retries` option to configure or disable retry settings:
|
|
214
|
-
|
|
215
|
-
```python
|
|
216
|
-
from tzafon import Computer
|
|
217
|
-
|
|
218
|
-
# Configure the default for all requests:
|
|
219
|
-
client = Computer(
|
|
220
|
-
# default is 2
|
|
221
|
-
max_retries=0,
|
|
222
|
-
)
|
|
223
|
-
|
|
224
|
-
# Or, configure per-request:
|
|
225
|
-
client.with_options(max_retries=5).computers.create(
|
|
226
|
-
kind="browser",
|
|
227
|
-
)
|
|
228
|
-
```
|
|
229
|
-
|
|
230
|
-
### Timeouts
|
|
231
|
-
|
|
232
|
-
By default requests time out after 1 minute. You can configure this with a `timeout` option,
|
|
233
|
-
which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object:
|
|
234
|
-
|
|
235
|
-
```python
|
|
236
|
-
from tzafon import Computer
|
|
237
|
-
|
|
238
|
-
# Configure the default for all requests:
|
|
239
|
-
client = Computer(
|
|
240
|
-
# 20 seconds (default is 1 minute)
|
|
241
|
-
timeout=20.0,
|
|
242
|
-
)
|
|
243
|
-
|
|
244
|
-
# More granular control:
|
|
245
|
-
client = Computer(
|
|
246
|
-
timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
|
|
247
|
-
)
|
|
248
|
-
|
|
249
|
-
# Override per-request:
|
|
250
|
-
client.with_options(timeout=5.0).computers.create(
|
|
251
|
-
kind="browser",
|
|
252
|
-
)
|
|
253
|
-
```
|
|
254
|
-
|
|
255
|
-
On timeout, an `APITimeoutError` is thrown.
|
|
256
|
-
|
|
257
|
-
Note that requests that time out are [retried twice by default](https://github.com/tzafon/computer-python/tree/main/#retries).
|
|
258
|
-
|
|
259
|
-
## Advanced
|
|
260
|
-
|
|
261
|
-
### Logging
|
|
262
|
-
|
|
263
|
-
We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.
|
|
264
|
-
|
|
265
|
-
You can enable logging by setting the environment variable `COMPUTER_LOG` to `info`.
|
|
266
|
-
|
|
267
|
-
```shell
|
|
268
|
-
$ export COMPUTER_LOG=info
|
|
269
|
-
```
|
|
270
|
-
|
|
271
|
-
Or to `debug` for more verbose logging.
|
|
272
|
-
|
|
273
|
-
### How to tell whether `None` means `null` or missing
|
|
274
|
-
|
|
275
|
-
In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`:
|
|
276
|
-
|
|
277
|
-
```py
|
|
278
|
-
if response.my_field is None:
|
|
279
|
-
if 'my_field' not in response.model_fields_set:
|
|
280
|
-
print('Got json like {}, without a "my_field" key present at all.')
|
|
281
|
-
else:
|
|
282
|
-
print('Got json like {"my_field": null}.')
|
|
283
|
-
```
|
|
284
|
-
|
|
285
|
-
### Accessing raw response data (e.g. headers)
|
|
286
|
-
|
|
287
|
-
The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,
|
|
288
|
-
|
|
289
|
-
```py
|
|
290
|
-
from tzafon import Computer
|
|
291
|
-
|
|
292
|
-
client = Computer()
|
|
293
|
-
response = client.computers.with_raw_response.create(
|
|
294
|
-
kind="browser",
|
|
295
|
-
)
|
|
296
|
-
print(response.headers.get('X-My-Header'))
|
|
297
|
-
|
|
298
|
-
computer = response.parse() # get the object that `computers.create()` would have returned
|
|
299
|
-
print(computer.id)
|
|
300
|
-
```
|
|
301
|
-
|
|
302
|
-
These methods return an [`APIResponse`](https://github.com/tzafon/computer-python/tree/main/src/tzafon/_response.py) object.
|
|
303
|
-
|
|
304
|
-
The async client returns an [`AsyncAPIResponse`](https://github.com/tzafon/computer-python/tree/main/src/tzafon/_response.py) with the same structure, the only difference being `await`able methods for reading the response content.
|
|
305
|
-
|
|
306
|
-
#### `.with_streaming_response`
|
|
307
|
-
|
|
308
|
-
The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
|
|
309
|
-
|
|
310
|
-
To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.
|
|
311
|
-
|
|
312
|
-
```python
|
|
313
|
-
with client.computers.with_streaming_response.create(
|
|
314
|
-
kind="browser",
|
|
315
|
-
) as response:
|
|
316
|
-
print(response.headers.get("X-My-Header"))
|
|
317
|
-
|
|
318
|
-
for line in response.iter_lines():
|
|
319
|
-
print(line)
|
|
320
|
-
```
|
|
321
|
-
|
|
322
|
-
The context manager is required so that the response will reliably be closed.
|
|
323
|
-
|
|
324
|
-
### Making custom/undocumented requests
|
|
325
|
-
|
|
326
|
-
This library is typed for convenient access to the documented API.
|
|
327
|
-
|
|
328
|
-
If you need to access undocumented endpoints, params, or response properties, the library can still be used.
|
|
329
|
-
|
|
330
|
-
#### Undocumented endpoints
|
|
331
|
-
|
|
332
|
-
To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other
|
|
333
|
-
http verbs. Options on the client will be respected (such as retries) when making this request.
|
|
334
|
-
|
|
335
|
-
```py
|
|
336
|
-
import httpx
|
|
337
|
-
|
|
338
|
-
response = client.post(
|
|
339
|
-
"/foo",
|
|
340
|
-
cast_to=httpx.Response,
|
|
341
|
-
body={"my_param": True},
|
|
342
|
-
)
|
|
343
|
-
|
|
344
|
-
print(response.headers.get("x-foo"))
|
|
345
|
-
```
|
|
346
|
-
|
|
347
|
-
#### Undocumented request params
|
|
348
|
-
|
|
349
|
-
If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request
|
|
350
|
-
options.
|
|
351
|
-
|
|
352
|
-
#### Undocumented response properties
|
|
353
|
-
|
|
354
|
-
To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You
|
|
355
|
-
can also get all the extra fields on the Pydantic model as a dict with
|
|
356
|
-
[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).
|
|
357
|
-
|
|
358
|
-
### Configuring the HTTP client
|
|
359
|
-
|
|
360
|
-
You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:
|
|
361
|
-
|
|
362
|
-
- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)
|
|
363
|
-
- Custom [transports](https://www.python-httpx.org/advanced/transports/)
|
|
364
|
-
- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality
|
|
365
|
-
|
|
366
|
-
```python
|
|
367
|
-
import httpx
|
|
368
|
-
from tzafon import Computer, DefaultHttpxClient
|
|
369
|
-
|
|
370
|
-
client = Computer(
|
|
371
|
-
# Or use the `COMPUTER_BASE_URL` env var
|
|
372
|
-
base_url="http://my.test.server.example.com:8083",
|
|
373
|
-
http_client=DefaultHttpxClient(
|
|
374
|
-
proxy="http://my.test.proxy.example.com",
|
|
375
|
-
transport=httpx.HTTPTransport(local_address="0.0.0.0"),
|
|
376
|
-
),
|
|
377
|
-
)
|
|
378
|
-
```
|
|
379
|
-
|
|
380
|
-
You can also customize the client on a per-request basis by using `with_options()`:
|
|
381
|
-
|
|
382
|
-
```python
|
|
383
|
-
client.with_options(http_client=DefaultHttpxClient(...))
|
|
384
|
-
```
|
|
385
|
-
|
|
386
|
-
### Managing HTTP resources
|
|
387
|
-
|
|
388
|
-
By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.
|
|
389
|
-
|
|
390
|
-
```py
|
|
391
|
-
from tzafon import Computer
|
|
392
|
-
|
|
393
|
-
with Computer() as client:
|
|
394
|
-
# make requests here
|
|
395
|
-
...
|
|
396
|
-
|
|
397
|
-
# HTTP client is now closed
|
|
398
|
-
```
|
|
399
|
-
|
|
400
|
-
## Versioning
|
|
401
|
-
|
|
402
|
-
This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
|
|
403
|
-
|
|
404
|
-
1. Changes that only affect static types, without breaking runtime behavior.
|
|
405
|
-
2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_
|
|
406
|
-
3. Changes that we do not expect to impact the vast majority of users in practice.
|
|
407
|
-
|
|
408
|
-
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
|
|
409
|
-
|
|
410
|
-
We are keen for your feedback; please open an [issue](https://www.github.com/tzafon/computer-python/issues) with questions, bugs, or suggestions.
|
|
411
|
-
|
|
412
|
-
### Determining the installed version
|
|
413
|
-
|
|
414
|
-
If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.
|
|
415
|
-
|
|
416
|
-
You can determine the version that is being used at runtime with:
|
|
417
|
-
|
|
418
|
-
```py
|
|
419
|
-
import tzafon
|
|
420
|
-
print(tzafon.__version__)
|
|
421
|
-
```
|
|
422
|
-
|
|
423
|
-
## Requirements
|
|
424
|
-
|
|
425
|
-
Python 3.8 or higher.
|
|
426
|
-
|
|
427
|
-
## Contributing
|
|
428
|
-
|
|
429
|
-
See [the contributing documentation](https://github.com/tzafon/computer-python/tree/main/./CONTRIBUTING.md).
|
|
File without changes
|
|
File without changes
|