anyenv 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.
anyenv/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ __version__ = "0.1.0"
2
+
3
+ from anyenv.threadgroup.threadgroup import ThreadGroup
4
+
5
+ __all__ = ["ThreadGroup"]
@@ -0,0 +1 @@
1
+ """AnyEnv download backend implementations."""
@@ -0,0 +1,179 @@
1
+ """aiohttp backend implementation for anyenv."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import pathlib
7
+ from typing import Any
8
+
9
+ import aiohttp
10
+ from aiohttp_client_cache import CachedSession, SQLiteBackend
11
+
12
+ from anyenv.download.base import (
13
+ HttpBackend,
14
+ HttpResponse,
15
+ Method,
16
+ ProgressCallback,
17
+ Session,
18
+ )
19
+
20
+
21
+ class AiohttpResponse(HttpResponse):
22
+ """aiohttp implementation of HTTP response."""
23
+
24
+ def __init__(self, response: aiohttp.ClientResponse) -> None:
25
+ self._response = response
26
+
27
+ @property
28
+ def status_code(self) -> int:
29
+ return self._response.status
30
+
31
+ @property
32
+ def headers(self) -> dict[str, str]:
33
+ return dict(self._response.headers)
34
+
35
+ async def text(self) -> str:
36
+ return await self._response.text()
37
+
38
+ async def json(self) -> Any:
39
+ return await self._response.json()
40
+
41
+ async def bytes(self) -> bytes:
42
+ return await self._response.read()
43
+
44
+
45
+ class AiohttpSession(Session):
46
+ """aiohttp implementation of HTTP session."""
47
+
48
+ def __init__(
49
+ self,
50
+ session: CachedSession,
51
+ base_url: str | None = None,
52
+ ) -> None:
53
+ self._session = session
54
+ self._base_url = base_url
55
+
56
+ async def request(
57
+ self,
58
+ method: Method,
59
+ url: str,
60
+ *,
61
+ params: dict[str, str] | None = None,
62
+ headers: dict[str, str] | None = None,
63
+ json: Any = None,
64
+ data: Any = None,
65
+ timeout: float | None = None,
66
+ cache: bool = False,
67
+ ) -> HttpResponse:
68
+ if self._base_url:
69
+ url = f"{self._base_url.rstrip('/')}/{url.lstrip('/')}"
70
+
71
+ response = await self._session.request(
72
+ method,
73
+ url,
74
+ params=params,
75
+ headers=headers,
76
+ json=json,
77
+ data=data,
78
+ timeout=aiohttp.ClientTimeout(total=timeout) if timeout else None,
79
+ expire_after=0 if not cache else None, # Don't cache if cache=False
80
+ )
81
+ return AiohttpResponse(response)
82
+
83
+ async def close(self) -> None:
84
+ await self._session.close()
85
+
86
+
87
+ class AiohttpBackend(HttpBackend):
88
+ """aiohttp implementation of HTTP backend."""
89
+
90
+ async def _create_session(
91
+ self,
92
+ cache: bool = False,
93
+ base_url: str | None = None,
94
+ headers: dict[str, str] | None = None,
95
+ ) -> CachedSession:
96
+ if cache:
97
+ cache_backend = SQLiteBackend(
98
+ cache_name=os.path.join(self.cache_dir, "http_cache.db"),
99
+ expire_after=self.cache_ttl,
100
+ )
101
+ return CachedSession(
102
+ cache=cache_backend,
103
+ headers=headers,
104
+ base_url=base_url,
105
+ )
106
+
107
+ # Even when not caching, we use CachedSession for consistent interface
108
+ return CachedSession(
109
+ expire_after=0, # Disable caching
110
+ headers=headers,
111
+ base_url=base_url,
112
+ )
113
+
114
+ async def request(
115
+ self,
116
+ method: Method,
117
+ url: str,
118
+ *,
119
+ params: dict[str, str] | None = None,
120
+ headers: dict[str, str] | None = None,
121
+ json: Any = None,
122
+ data: Any = None,
123
+ timeout: float | None = None,
124
+ cache: bool = False,
125
+ ) -> HttpResponse:
126
+ session = await self._create_session(cache=cache)
127
+ try:
128
+ response = await session.request(
129
+ method,
130
+ url,
131
+ params=params,
132
+ headers=headers,
133
+ json=json,
134
+ data=data,
135
+ timeout=aiohttp.ClientTimeout(total=timeout) if timeout else None,
136
+ )
137
+ return AiohttpResponse(response)
138
+ finally:
139
+ await session.close()
140
+
141
+ async def download(
142
+ self,
143
+ url: str,
144
+ path: str | os.PathLike[str],
145
+ *,
146
+ headers: dict[str, str] | None = None,
147
+ progress_callback: ProgressCallback | None = None,
148
+ cache: bool = False,
149
+ ) -> None:
150
+ session = await self._create_session(cache=cache)
151
+ try:
152
+ async with session.get(url, headers=headers) as response:
153
+ response.raise_for_status()
154
+
155
+ total = int(response.headers.get("content-length", "0"))
156
+ current = 0
157
+
158
+ with pathlib.Path(path).open("wb") as f:
159
+ async for chunk in response.content.iter_chunked(8192):
160
+ f.write(chunk)
161
+ current += len(chunk)
162
+ if progress_callback:
163
+ await self._handle_callback(progress_callback, current, total)
164
+ finally:
165
+ await session.close()
166
+
167
+ async def create_session(
168
+ self,
169
+ *,
170
+ base_url: str | None = None,
171
+ headers: dict[str, str] | None = None,
172
+ cache: bool = False,
173
+ ) -> Session:
174
+ session = await self._create_session(
175
+ cache=cache,
176
+ base_url=base_url,
177
+ headers=headers,
178
+ )
179
+ return AiohttpSession(session, base_url)
@@ -0,0 +1,249 @@
1
+ """Base classes for anyenv HTTP functionality."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import abc
6
+ from collections.abc import Callable
7
+ import inspect
8
+ from typing import TYPE_CHECKING, Any, Literal, Self, TypeVar
9
+
10
+ import anyio
11
+ from appdirs import user_cache_dir
12
+
13
+
14
+ if TYPE_CHECKING:
15
+ from os import PathLike
16
+ import types
17
+
18
+ T = TypeVar("T")
19
+ ProgressCallback = Callable[[int, int], Any] # current, total -> Any
20
+ Method = Literal["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"]
21
+
22
+
23
+ class HttpResponse(abc.ABC):
24
+ """HTTP response object."""
25
+
26
+ @property
27
+ @abc.abstractmethod
28
+ def status_code(self) -> int:
29
+ """HTTP status code."""
30
+ raise NotImplementedError
31
+
32
+ @property
33
+ @abc.abstractmethod
34
+ def headers(self) -> dict[str, str]:
35
+ """Response headers."""
36
+ raise NotImplementedError
37
+
38
+ @abc.abstractmethod
39
+ async def text(self) -> str:
40
+ """Get response body as text."""
41
+ raise NotImplementedError
42
+
43
+ @abc.abstractmethod
44
+ async def json(self) -> Any:
45
+ """Get response body as JSON."""
46
+ raise NotImplementedError
47
+
48
+ @abc.abstractmethod
49
+ async def bytes(self) -> bytes:
50
+ """Get response body as bytes."""
51
+ raise NotImplementedError
52
+
53
+
54
+ class Session(abc.ABC):
55
+ """HTTP session for connection reuse."""
56
+
57
+ @abc.abstractmethod
58
+ async def request(
59
+ self,
60
+ method: Method,
61
+ url: str,
62
+ *,
63
+ params: dict[str, str] | None = None,
64
+ headers: dict[str, str] | None = None,
65
+ json: Any = None,
66
+ data: Any = None,
67
+ timeout: float | None = None,
68
+ cache: bool = False,
69
+ ) -> HttpResponse:
70
+ """Make a request."""
71
+ raise NotImplementedError
72
+
73
+ @abc.abstractmethod
74
+ async def close(self) -> None:
75
+ """Close the session."""
76
+ raise NotImplementedError
77
+
78
+ async def __aenter__(self) -> Self:
79
+ """Enter async context."""
80
+ return self
81
+
82
+ async def __aexit__(
83
+ self,
84
+ exc_type: type[BaseException] | None,
85
+ exc_val: BaseException | None,
86
+ exc_tb: types.TracebackType | None,
87
+ ) -> None:
88
+ """Exit async context."""
89
+ await self.close()
90
+
91
+ def __enter__(self) -> Self:
92
+ """Enter sync context."""
93
+
94
+ async def wrapper() -> Self:
95
+ return await self.__aenter__()
96
+
97
+ return anyio.run(wrapper)
98
+
99
+ def __exit__(
100
+ self,
101
+ exc_type: type[BaseException] | None,
102
+ exc_val: BaseException | None,
103
+ exc_tb: types.TracebackType | None,
104
+ ) -> None:
105
+ """Exit sync context."""
106
+
107
+ async def wrapper() -> None:
108
+ await self.__aexit__(exc_type, exc_val, exc_tb)
109
+
110
+ anyio.run(wrapper)
111
+
112
+
113
+ class HttpBackend(abc.ABC):
114
+ """Base class for HTTP backend implementations."""
115
+
116
+ def __init__(
117
+ self,
118
+ cache_dir: str | PathLike[str] | None = None,
119
+ cache_ttl: int = 3600,
120
+ ) -> None:
121
+ """Initialize HTTP backend.
122
+
123
+ Args:
124
+ cache_dir: Directory to store cached responses. If None,
125
+ uses platform-specific user cache directory.
126
+ cache_ttl: Time-to-live for cached responses in seconds.
127
+ """
128
+ self.cache_dir = cache_dir or user_cache_dir("anyenv", "anyenv")
129
+ self.cache_ttl = cache_ttl
130
+
131
+ @abc.abstractmethod
132
+ async def request(
133
+ self,
134
+ method: Method,
135
+ url: str,
136
+ *,
137
+ params: dict[str, str] | None = None,
138
+ headers: dict[str, str] | None = None,
139
+ json: Any = None,
140
+ data: Any = None,
141
+ timeout: float | None = None,
142
+ cache: bool = False,
143
+ ) -> HttpResponse:
144
+ """Make a request."""
145
+ raise NotImplementedError
146
+
147
+ def request_sync(
148
+ self,
149
+ method: Method,
150
+ url: str,
151
+ *,
152
+ params: dict[str, str] | None = None,
153
+ headers: dict[str, str] | None = None,
154
+ json: Any = None,
155
+ data: Any = None,
156
+ timeout: float | None = None,
157
+ cache: bool = False,
158
+ ) -> HttpResponse:
159
+ """Synchronous version of request."""
160
+
161
+ async def wrapper() -> HttpResponse:
162
+ return await self.request(
163
+ method,
164
+ url,
165
+ params=params,
166
+ headers=headers,
167
+ json=json,
168
+ data=data,
169
+ timeout=timeout,
170
+ cache=cache,
171
+ )
172
+
173
+ return anyio.run(wrapper)
174
+
175
+ @abc.abstractmethod
176
+ async def download(
177
+ self,
178
+ url: str,
179
+ path: str | PathLike[str],
180
+ *,
181
+ headers: dict[str, str] | None = None,
182
+ progress_callback: ProgressCallback | None = None,
183
+ cache: bool = False,
184
+ ) -> None:
185
+ """Download a file with optional progress reporting."""
186
+ raise NotImplementedError
187
+
188
+ def download_sync(
189
+ self,
190
+ url: str,
191
+ path: str | PathLike[str],
192
+ *,
193
+ headers: dict[str, str] | None = None,
194
+ progress_callback: ProgressCallback | None = None,
195
+ cache: bool = False,
196
+ ) -> None:
197
+ """Synchronous version of download."""
198
+
199
+ async def wrapper() -> None:
200
+ await self.download(
201
+ url,
202
+ path,
203
+ headers=headers,
204
+ progress_callback=progress_callback,
205
+ cache=cache,
206
+ )
207
+
208
+ return anyio.run(wrapper)
209
+
210
+ @abc.abstractmethod
211
+ async def create_session(
212
+ self,
213
+ *,
214
+ base_url: str | None = None,
215
+ headers: dict[str, str] | None = None,
216
+ cache: bool = False,
217
+ ) -> Session:
218
+ """Create a new session for connection reuse."""
219
+ raise NotImplementedError
220
+
221
+ def create_session_sync(
222
+ self,
223
+ *,
224
+ base_url: str | None = None,
225
+ headers: dict[str, str] | None = None,
226
+ cache: bool = False,
227
+ ) -> Session:
228
+ """Synchronous version of create_session."""
229
+
230
+ async def wrapper() -> Session:
231
+ return await self.create_session(
232
+ base_url=base_url,
233
+ headers=headers,
234
+ cache=cache,
235
+ )
236
+
237
+ return anyio.run(wrapper)
238
+
239
+ async def _handle_callback(
240
+ self,
241
+ callback: ProgressCallback,
242
+ current: int,
243
+ total: int,
244
+ ) -> None:
245
+ """Handle both sync and async callbacks."""
246
+ if inspect.iscoroutinefunction(callback):
247
+ await callback(current, total)
248
+ else:
249
+ callback(current, total)
@@ -0,0 +1,17 @@
1
+ """Exceptions anyenv HTTP functionality."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+
8
+ if TYPE_CHECKING:
9
+ from anyenv.download.base import HttpResponse
10
+
11
+
12
+ class HttpError(Exception):
13
+ """Base class for HTTP errors."""
14
+
15
+ def __init__(self, message: str, response: HttpResponse | None = None) -> None:
16
+ super().__init__(message)
17
+ self.response = response
@@ -0,0 +1,198 @@
1
+ """HTTPX backend implementation for anyenv."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pathlib
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ import hishel
9
+ import httpx
10
+
11
+ from anyenv.download.base import (
12
+ HttpBackend,
13
+ HttpResponse,
14
+ Method,
15
+ ProgressCallback,
16
+ Session,
17
+ )
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ import os
22
+
23
+
24
+ class HttpxResponse(HttpResponse):
25
+ """HTTPX implementation of HTTP response."""
26
+
27
+ def __init__(self, response: httpx.Response) -> None:
28
+ self._response = response
29
+
30
+ @property
31
+ def status_code(self) -> int:
32
+ return self._response.status_code
33
+
34
+ @property
35
+ def headers(self) -> dict[str, str]:
36
+ return dict(self._response.headers)
37
+
38
+ async def text(self) -> str:
39
+ return self._response.text
40
+
41
+ async def json(self) -> Any:
42
+ return self._response.json()
43
+
44
+ async def bytes(self) -> bytes:
45
+ return self._response.content
46
+
47
+
48
+ class HttpxSession(Session):
49
+ """HTTPX implementation of HTTP session."""
50
+
51
+ def __init__(
52
+ self,
53
+ client: httpx.AsyncClient,
54
+ base_url: str | None = None,
55
+ ) -> None:
56
+ self._client = client
57
+ self._base_url = base_url
58
+
59
+ async def request(
60
+ self,
61
+ method: Method,
62
+ url: str,
63
+ *,
64
+ params: dict[str, str] | None = None,
65
+ headers: dict[str, str] | None = None,
66
+ json: Any = None,
67
+ data: Any = None,
68
+ timeout: float | None = None,
69
+ cache: bool = False,
70
+ ) -> HttpResponse:
71
+ if self._base_url:
72
+ url = f"{self._base_url.rstrip('/')}/{url.lstrip('/')}"
73
+
74
+ response = await self._client.request(
75
+ method,
76
+ url,
77
+ params=params,
78
+ headers=headers,
79
+ json=json,
80
+ data=data,
81
+ timeout=timeout if timeout else None,
82
+ )
83
+ return HttpxResponse(response)
84
+
85
+ async def close(self) -> None:
86
+ await self._client.aclose()
87
+
88
+
89
+ class HttpxBackend(HttpBackend):
90
+ """HTTPX implementation of HTTP backend."""
91
+
92
+ def _create_client(
93
+ self,
94
+ cache: bool = False,
95
+ base_url: str | None = None,
96
+ headers: dict[str, str] | None = None,
97
+ ) -> httpx.AsyncClient:
98
+ if cache:
99
+ storage = hishel.AsyncFileStorage(
100
+ base_path=self.cache_dir,
101
+ ttl=self.cache_ttl,
102
+ )
103
+ controller = hishel.Controller(
104
+ cacheable_methods=["GET"],
105
+ cacheable_status_codes=[200],
106
+ allow_stale=True,
107
+ )
108
+ transport = hishel.AsyncCacheTransport(
109
+ transport=httpx.AsyncHTTPTransport(),
110
+ storage=storage,
111
+ controller=controller,
112
+ )
113
+ return httpx.AsyncClient(
114
+ transport=transport,
115
+ headers=headers,
116
+ base_url=base_url or "",
117
+ )
118
+
119
+ return httpx.AsyncClient(
120
+ headers=headers,
121
+ base_url=base_url or "",
122
+ )
123
+
124
+ async def request(
125
+ self,
126
+ method: Method,
127
+ url: str,
128
+ *,
129
+ params: dict[str, str] | None = None,
130
+ headers: dict[str, str] | None = None,
131
+ json: Any = None,
132
+ data: Any = None,
133
+ timeout: float | None = None,
134
+ cache: bool = False,
135
+ ) -> HttpResponse:
136
+ async with self._create_client(cache=cache) as client:
137
+ response = await client.request(
138
+ method,
139
+ url,
140
+ params=params,
141
+ headers=headers,
142
+ json=json,
143
+ data=data,
144
+ timeout=timeout if timeout else None,
145
+ )
146
+ return HttpxResponse(response)
147
+
148
+ async def download(
149
+ self,
150
+ url: str,
151
+ path: str | os.PathLike[str],
152
+ *,
153
+ headers: dict[str, str] | None = None,
154
+ progress_callback: ProgressCallback | None = None,
155
+ cache: bool = False,
156
+ ) -> None:
157
+ async with self._create_client(cache=cache) as client: # noqa: SIM117
158
+ async with client.stream("GET", url, headers=headers) as response:
159
+ response.raise_for_status()
160
+
161
+ total = int(response.headers.get("content-length", "0"))
162
+ current = 0
163
+
164
+ with pathlib.Path(path).open("wb") as f:
165
+ async for chunk in response.aiter_bytes():
166
+ f.write(chunk)
167
+ current += len(chunk)
168
+ if progress_callback:
169
+ await self._handle_callback(progress_callback, current, total)
170
+
171
+ async def create_session(
172
+ self,
173
+ *,
174
+ base_url: str | None = None,
175
+ headers: dict[str, str] | None = None,
176
+ cache: bool = False,
177
+ ) -> Session:
178
+ client = self._create_client(
179
+ cache=cache,
180
+ base_url=base_url,
181
+ headers=headers,
182
+ )
183
+ return HttpxSession(client, base_url)
184
+
185
+
186
+ if __name__ == "__main__":
187
+
188
+ async def main():
189
+ backend = HttpxBackend()
190
+ await backend.download(
191
+ url="http://speedtest.tele2.net/10MB.zip",
192
+ path=pathlib.Path.cwd() / "file.zip",
193
+ headers={"User-Agent": "anyenv"},
194
+ )
195
+
196
+ import anyio
197
+
198
+ anyio.run(main)
@@ -0,0 +1,177 @@
1
+ """Pyodide backend implementation for anyenv."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json as json_lib
6
+ import pathlib
7
+ from typing import TYPE_CHECKING, Any
8
+ from urllib.parse import urljoin
9
+
10
+ from anyenv.download.base import (
11
+ HttpBackend,
12
+ HttpResponse,
13
+ Method,
14
+ ProgressCallback,
15
+ Session,
16
+ )
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ import os
21
+
22
+ from pyodide.http import FetchResponse
23
+
24
+
25
+ class PyodideResponse(HttpResponse):
26
+ """Pyodide implementation of HTTP response."""
27
+
28
+ def __init__(self, response: FetchResponse) -> None:
29
+ self._response = response
30
+
31
+ @property
32
+ def status_code(self) -> int:
33
+ return self._response.status
34
+
35
+ @property
36
+ def headers(self) -> dict[str, str]:
37
+ return dict(self._response.headers)
38
+
39
+ async def text(self) -> str:
40
+ return await self._response.string()
41
+
42
+ async def json(self) -> Any:
43
+ return await self._response.json()
44
+
45
+ async def bytes(self) -> bytes:
46
+ return await self._response.bytes()
47
+
48
+
49
+ class PyodideSession(Session):
50
+ """Pyodide implementation of HTTP session.
51
+
52
+ Note: In Pyodide/browser environment, we can't maintain persistent connections.
53
+ Each request is independent, but we maintain consistent headers and base URL.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ base_url: str | None = None,
59
+ headers: dict[str, str] | None = None,
60
+ ) -> None:
61
+ self._base_url = base_url
62
+ self._headers = headers or {}
63
+
64
+ async def request(
65
+ self,
66
+ method: Method,
67
+ url: str,
68
+ *,
69
+ params: dict[str, str] | None = None,
70
+ headers: dict[str, str] | None = None,
71
+ json: Any = None,
72
+ data: Any = None,
73
+ timeout: float | None = None,
74
+ cache: bool = False,
75
+ ) -> HttpResponse:
76
+ # Merge session headers with request headers
77
+ from pyodide.http import pyfetch
78
+
79
+ request_headers = self._headers.copy()
80
+ if headers:
81
+ request_headers.update(headers)
82
+
83
+ # Handle base URL
84
+ if self._base_url:
85
+ url = urljoin(self._base_url, url)
86
+
87
+ # Prepare request options
88
+ options: dict[str, Any] = {
89
+ "method": method,
90
+ "headers": request_headers,
91
+ "mode": "cors",
92
+ }
93
+
94
+ # Handle body data
95
+ if json is not None:
96
+ options["body"] = json_lib.dumps(json)
97
+ request_headers["Content-Type"] = "application/json"
98
+ elif data is not None:
99
+ options["body"] = data
100
+
101
+ # Handle caching
102
+ if cache:
103
+ options["cache"] = "force-cache"
104
+ else:
105
+ options["cache"] = "no-store"
106
+
107
+ response = await pyfetch(url, **options)
108
+ return PyodideResponse(response)
109
+
110
+ async def close(self) -> None:
111
+ """No-op in Pyodide as there's no persistent connection."""
112
+
113
+
114
+ class PyodideBackend(HttpBackend):
115
+ """Pyodide implementation of HTTP backend."""
116
+
117
+ async def request(
118
+ self,
119
+ method: Method,
120
+ url: str,
121
+ *,
122
+ params: dict[str, str] | None = None,
123
+ headers: dict[str, str] | None = None,
124
+ json: Any = None,
125
+ data: Any = None,
126
+ timeout: float | None = None,
127
+ cache: bool = False,
128
+ ) -> HttpResponse:
129
+ session = PyodideSession()
130
+ return await session.request(
131
+ method,
132
+ url,
133
+ params=params,
134
+ headers=headers,
135
+ json=json,
136
+ data=data,
137
+ timeout=timeout,
138
+ cache=cache,
139
+ )
140
+
141
+ async def download(
142
+ self,
143
+ url: str,
144
+ path: str | os.PathLike[str],
145
+ *,
146
+ headers: dict[str, str] | None = None,
147
+ progress_callback: ProgressCallback | None = None,
148
+ cache: bool = False,
149
+ ) -> None:
150
+ # In browser environment, we need to get the full response first
151
+ from pyodide.http import pyfetch
152
+
153
+ response = await pyfetch(
154
+ url,
155
+ headers=headers,
156
+ cache="force-cache" if cache else "no-store",
157
+ )
158
+
159
+ content = await response.bytes()
160
+ total = len(content)
161
+
162
+ # Write to file and handle progress
163
+ with pathlib.Path(path).open("wb") as f:
164
+ if progress_callback:
165
+ await self._handle_callback(progress_callback, 0, total)
166
+ f.write(content)
167
+ if progress_callback:
168
+ await self._handle_callback(progress_callback, total, total)
169
+
170
+ async def create_session(
171
+ self,
172
+ *,
173
+ base_url: str | None = None,
174
+ headers: dict[str, str] | None = None,
175
+ cache: bool = False,
176
+ ) -> Session:
177
+ return PyodideSession(base_url=base_url, headers=headers)
anyenv/py.typed ADDED
File without changes
File without changes
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ import concurrent.futures
4
+ import logging
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from typing_extensions import TypeVar
8
+
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Callable
12
+
13
+
14
+ R = TypeVar("R", default=Any)
15
+
16
+
17
+ class ThreadGroup[R]:
18
+ def __init__(self, max_workers: int | None = None, raise_exceptions: bool = True):
19
+ """Thread task group that executes functions in parallel.
20
+
21
+ Supports both sync and async context managers.
22
+
23
+ Args:
24
+ max_workers: Maximum number of worker threads
25
+ raise_exceptions: If True, raises exceptions from tasks
26
+ """
27
+ self.max_workers = max_workers
28
+ self.raise_exceptions = raise_exceptions
29
+ self.executor = concurrent.futures.ThreadPoolExecutor(
30
+ max_workers=self.max_workers
31
+ )
32
+ self.futures: list[concurrent.futures.Future[R]] = []
33
+ self._results: list[R] = []
34
+ self._exceptions: list[Exception] = []
35
+ self._logger = logging.getLogger(self.__class__.__name__)
36
+
37
+ def spawn(self, func: Callable[..., R], *args: Any, **kwargs: Any) -> None:
38
+ """Submit a task immediately to the executor."""
39
+ future = self.executor.submit(func, *args, **kwargs)
40
+ self.futures.append(future)
41
+
42
+ def __enter__(self) -> ThreadGroup[R]:
43
+ return self
44
+
45
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
46
+ for future in concurrent.futures.as_completed(self.futures):
47
+ try:
48
+ result = future.result()
49
+ self._results.append(result)
50
+ except Exception as e:
51
+ self._exceptions.append(e)
52
+ self._logger.exception("Task error")
53
+ if self.raise_exceptions:
54
+ raise
55
+
56
+ self.futures = []
57
+
58
+ async def __aenter__(self) -> ThreadGroup[R]:
59
+ return self.__enter__()
60
+
61
+ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
62
+ import asyncio
63
+
64
+ loop = asyncio.get_running_loop()
65
+ await loop.run_in_executor(None, lambda: self.__exit__(exc_type, exc_val, exc_tb))
66
+
67
+ def shutdown(self) -> None:
68
+ """Shutdown the executor when done with the ThreadGroup."""
69
+ self.executor.shutdown()
70
+
71
+ @property
72
+ def results(self) -> list[R]:
73
+ return self._results
74
+
75
+ @property
76
+ def exceptions(self) -> list[Exception]:
77
+ return self._exceptions
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: anyenv
3
+ Version: 0.1.0
4
+ Summary: Compatibility layer for some basic operations to allow painless operation in PyOdide and Python pre-releases
5
+ Project-URL: Documentation, https://phil65.github.io/anyenv/
6
+ Project-URL: Source, https://github.com/phil65/anyenv
7
+ Project-URL: Issues, https://github.com/phil65/anyenv/issues
8
+ Project-URL: Discussions, https://github.com/phil65/anyenv/discussions
9
+ Project-URL: Code coverage, https://app.codecov.io/gh/phil65/anyenv
10
+ Author-email: Philipp Temminghoff <philipptemminghoff@googlemail.com>
11
+ License: MIT License
12
+
13
+ Copyright (c) 2024, Philipp Temminghoff
14
+
15
+ Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ of this software and associated documentation files (the "Software"), to deal
17
+ in the Software without restriction, including without limitation the rights
18
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ copies of the Software, and to permit persons to whom the Software is
20
+ furnished to do so, subject to the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be included in all
23
+ copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ SOFTWARE.
32
+
33
+ License-File: LICENSE
34
+ Classifier: Development Status :: 4 - Beta
35
+ Classifier: Intended Audience :: Developers
36
+ Classifier: Operating System :: OS Independent
37
+ Classifier: Programming Language :: Python :: 3
38
+ Classifier: Programming Language :: Python :: 3 :: Only
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Programming Language :: Python :: 3.13
41
+ Classifier: Programming Language :: Python :: 3.14
42
+ Classifier: Topic :: Documentation
43
+ Classifier: Topic :: Software Development
44
+ Classifier: Topic :: Utilities
45
+ Classifier: Typing :: Typed
46
+ Requires-Python: >=3.12
47
+ Requires-Dist: anyio>=4.8.0
48
+ Requires-Dist: appdirs>=1.4.4
49
+ Provides-Extra: aiohttp
50
+ Requires-Dist: aiohttp; extra == 'aiohttp'
51
+ Requires-Dist: aiohttp-client-cache; extra == 'aiohttp'
52
+ Provides-Extra: httpx
53
+ Requires-Dist: hishel; extra == 'httpx'
54
+ Requires-Dist: httpx; extra == 'httpx'
55
+ Description-Content-Type: text/markdown
56
+
57
+ # AnyEnv
58
+
59
+ [![PyPI License](https://img.shields.io/pypi/l/anyenv.svg)](https://pypi.org/project/anyenv/)
60
+ [![Package status](https://img.shields.io/pypi/status/anyenv.svg)](https://pypi.org/project/anyenv/)
61
+ [![Daily downloads](https://img.shields.io/pypi/dd/anyenv.svg)](https://pypi.org/project/anyenv/)
62
+ [![Weekly downloads](https://img.shields.io/pypi/dw/anyenv.svg)](https://pypi.org/project/anyenv/)
63
+ [![Monthly downloads](https://img.shields.io/pypi/dm/anyenv.svg)](https://pypi.org/project/anyenv/)
64
+ [![Distribution format](https://img.shields.io/pypi/format/anyenv.svg)](https://pypi.org/project/anyenv/)
65
+ [![Wheel availability](https://img.shields.io/pypi/wheel/anyenv.svg)](https://pypi.org/project/anyenv/)
66
+ [![Python version](https://img.shields.io/pypi/pyversions/anyenv.svg)](https://pypi.org/project/anyenv/)
67
+ [![Implementation](https://img.shields.io/pypi/implementation/anyenv.svg)](https://pypi.org/project/anyenv/)
68
+ [![Releases](https://img.shields.io/github/downloads/phil65/anyenv/total.svg)](https://github.com/phil65/anyenv/releases)
69
+ [![Github Contributors](https://img.shields.io/github/contributors/phil65/anyenv)](https://github.com/phil65/anyenv/graphs/contributors)
70
+ [![Github Discussions](https://img.shields.io/github/discussions/phil65/anyenv)](https://github.com/phil65/anyenv/discussions)
71
+ [![Github Forks](https://img.shields.io/github/forks/phil65/anyenv)](https://github.com/phil65/anyenv/forks)
72
+ [![Github Issues](https://img.shields.io/github/issues/phil65/anyenv)](https://github.com/phil65/anyenv/issues)
73
+ [![Github Issues](https://img.shields.io/github/issues-pr/phil65/anyenv)](https://github.com/phil65/anyenv/pulls)
74
+ [![Github Watchers](https://img.shields.io/github/watchers/phil65/anyenv)](https://github.com/phil65/anyenv/watchers)
75
+ [![Github Stars](https://img.shields.io/github/stars/phil65/anyenv)](https://github.com/phil65/anyenv/stars)
76
+ [![Github Repository size](https://img.shields.io/github/repo-size/phil65/anyenv)](https://github.com/phil65/anyenv)
77
+ [![Github last commit](https://img.shields.io/github/last-commit/phil65/anyenv)](https://github.com/phil65/anyenv/commits)
78
+ [![Github release date](https://img.shields.io/github/release-date/phil65/anyenv)](https://github.com/phil65/anyenv/releases)
79
+ [![Github language count](https://img.shields.io/github/languages/count/phil65/anyenv)](https://github.com/phil65/anyenv)
80
+ [![Github commits this week](https://img.shields.io/github/commit-activity/w/phil65/anyenv)](https://github.com/phil65/anyenv)
81
+ [![Github commits this month](https://img.shields.io/github/commit-activity/m/phil65/anyenv)](https://github.com/phil65/anyenv)
82
+ [![Github commits this year](https://img.shields.io/github/commit-activity/y/phil65/anyenv)](https://github.com/phil65/anyenv)
83
+ [![Package status](https://codecov.io/gh/phil65/anyenv/branch/main/graph/badge.svg)](https://codecov.io/gh/phil65/anyenv/)
84
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
85
+ [![PyUp](https://pyup.io/repos/github/phil65/anyenv/shield.svg)](https://pyup.io/repos/github/phil65/anyenv/)
86
+
87
+ [Read the documentation!](https://phil65.github.io/anyenv/)
88
+
@@ -0,0 +1,14 @@
1
+ anyenv/__init__.py,sha256=IKBacqA3TvZ90Yx_f-qtfLwBjpWANB7kBBtuDwjKElE,110
2
+ anyenv/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ anyenv/download/__init__.py,sha256=VaQ0ylHIhE5CEsXhzX2hQruQqTpjX39bnATGNBr2Q_g,48
4
+ anyenv/download/aiohttp_backend.py,sha256=wj26wnxK0dz_mr5hyd31E4oBWazCqYjZOXK8eDaOgD4,5250
5
+ anyenv/download/base.py,sha256=30WEP5rrCy9ZAOVE3Cga-Iu1WIU-AQT24SD5rMrtS4E,6754
6
+ anyenv/download/exceptions.py,sha256=xQzfLczX4vAbZjCrMxfJSEJdupAYuIXuOeaxQNXrjmo,421
7
+ anyenv/download/httpx_backend.py,sha256=maMyqS6PSgGAwHNL4NVjSrNNmxNow-fty6N6p4FXfeE,5505
8
+ anyenv/download/pyodide_backend.py,sha256=kw888UwaiyLRgCwDWHSugJ8dv9ErZ_J_E9mFmzavFlg,4899
9
+ anyenv/threadgroup/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ anyenv/threadgroup/threadgroup.py,sha256=Tp_5qasprcE8HMUIHdNC4ISrg_fMll8-6LAVJjo2Hg4,2491
11
+ anyenv-0.1.0.dist-info/METADATA,sha256=s4GQuB18ygJGUmweHUS8k-E-c_GRHUMXSSb6AXG9xS8,5856
12
+ anyenv-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
13
+ anyenv-0.1.0.dist-info/licenses/LICENSE,sha256=AteGCH9r177TxxrOFEiOARrastASsf7yW6MQxlAHdwA,1078
14
+ anyenv-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024, Philipp Temminghoff
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.
22
+