fasttransport 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022, fastai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ include pyproject.toml
2
+ include LICENSE
3
+ include CONTRIBUTING.md
4
+ include README.md
5
+ recursive-exclude * __pycache__
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: fasttransport
3
+ Version: 0.0.1
4
+ Summary: Sync and async HTTP transports over httpx2, plus base classes for small REST clients
5
+ Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/AnswerDotAI/fasttransport
8
+ Project-URL: Documentation, https://AnswerDotAI.github.io/fasttransport/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: fastcore>=2.2.11
16
+ Requires-Dist: httpx2>=2.9.1
17
+ Provides-Extra: dev
18
+ Requires-Dist: cachy>=0.0.7; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # fasttransport
22
+
23
+
24
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
25
+
26
+ ## Install
27
+
28
+ ``` sh
29
+ pip install fasttransport
30
+ ```
31
+
32
+ ## Why
33
+
34
+ Every small API wrapper needs the same plumbing: headers merged into each request, responses decoded by content type, errors that carry the response body, and SSE parsing for streams. Most wrappers also repeat the same mistake. They create one httpx client at startup and keep it, which pins its pooled connections to the event loop that created them. Code that later runs under a different loop, common in tests and background tasks, then fails with confusing connection errors.
35
+
36
+ fasttransport is that plumbing written once, on [httpx2](https://github.com/pydantic/httpx2). Each request gets a fresh client and nothing is tied to a loop. Pass `client=` to manage a persistent client yourself. [fastspec](https://github.com/AnswerDotAI/fastspec) builds its spec-driven clients on these transports, [ghapi](https://github.com/AnswerDotAI/ghapi) its GitHub client, and [solveit](https://github.com/AnswerDotAI/solveit) its gateway clients.
37
+
38
+ ## Get started
39
+
40
+ [`SyncTransport.request`](https://AnswerDotAI.github.io/fasttransport/core.html#synctransport.request) executes a call and returns the decoded body: JSON arrives as a dict, text as text, and anything else as bytes. HTTP errors raise with the response body included in the message.
41
+
42
+ ``` python
43
+ from fasttransport.core import *
44
+ ```
45
+
46
+ ``` python
47
+ SyncTransport().request('GET', 'https://jsonplaceholder.typicode.com/todos/1')
48
+ ```
49
+
50
+ [`AsyncTransport`](https://AnswerDotAI.github.io/fasttransport/core.html#asynctransport) is the same, awaited. It also has `stream`, an async generator that parses SSE events into JSON dicts. The [core page](https://AnswerDotAI.github.io/fasttransport/core.html) streams a chat completion with it.
51
+
52
+ ``` python
53
+ await AsyncTransport().request('GET', 'https://jsonplaceholder.typicode.com/users/1')
54
+ ```
55
+
56
+ A small REST client is a base URL plus verbs. [`HttpCli`](https://AnswerDotAI.github.io/fasttransport/core.html#httpcli) verbs take a path relative to the base, kwargs become the payload (query params on `get` and `delete`, the JSON body otherwise), and decoded bodies come back:
57
+
58
+ ``` python
59
+ cli = HttpCli('https://jsonplaceholder.typicode.com')
60
+ cli.get('todos/1')
61
+ ```
62
+
63
+ ``` python
64
+ cli.post('posts', title='hi')
65
+ ```
66
+
67
+ [`AsyncHttpCli`](https://AnswerDotAI.github.io/fasttransport/core.html#asynchttpcli) is the async twin. Its verbs return awaitables:
68
+
69
+ ``` python
70
+ acli = AsyncHttpCli('https://jsonplaceholder.typicode.com')
71
+ await acli.get('todos/1')
72
+ ```
73
+
74
+ The [core page](https://AnswerDotAI.github.io/fasttransport/core.html) documents the rest with runnable examples: SSE streaming, error enrichment, multipart uploads, and managing your own client.
@@ -0,0 +1,54 @@
1
+ # fasttransport
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ ## Install
7
+
8
+ ``` sh
9
+ pip install fasttransport
10
+ ```
11
+
12
+ ## Why
13
+
14
+ Every small API wrapper needs the same plumbing: headers merged into each request, responses decoded by content type, errors that carry the response body, and SSE parsing for streams. Most wrappers also repeat the same mistake. They create one httpx client at startup and keep it, which pins its pooled connections to the event loop that created them. Code that later runs under a different loop, common in tests and background tasks, then fails with confusing connection errors.
15
+
16
+ fasttransport is that plumbing written once, on [httpx2](https://github.com/pydantic/httpx2). Each request gets a fresh client and nothing is tied to a loop. Pass `client=` to manage a persistent client yourself. [fastspec](https://github.com/AnswerDotAI/fastspec) builds its spec-driven clients on these transports, [ghapi](https://github.com/AnswerDotAI/ghapi) its GitHub client, and [solveit](https://github.com/AnswerDotAI/solveit) its gateway clients.
17
+
18
+ ## Get started
19
+
20
+ [`SyncTransport.request`](https://AnswerDotAI.github.io/fasttransport/core.html#synctransport.request) executes a call and returns the decoded body: JSON arrives as a dict, text as text, and anything else as bytes. HTTP errors raise with the response body included in the message.
21
+
22
+ ``` python
23
+ from fasttransport.core import *
24
+ ```
25
+
26
+ ``` python
27
+ SyncTransport().request('GET', 'https://jsonplaceholder.typicode.com/todos/1')
28
+ ```
29
+
30
+ [`AsyncTransport`](https://AnswerDotAI.github.io/fasttransport/core.html#asynctransport) is the same, awaited. It also has `stream`, an async generator that parses SSE events into JSON dicts. The [core page](https://AnswerDotAI.github.io/fasttransport/core.html) streams a chat completion with it.
31
+
32
+ ``` python
33
+ await AsyncTransport().request('GET', 'https://jsonplaceholder.typicode.com/users/1')
34
+ ```
35
+
36
+ A small REST client is a base URL plus verbs. [`HttpCli`](https://AnswerDotAI.github.io/fasttransport/core.html#httpcli) verbs take a path relative to the base, kwargs become the payload (query params on `get` and `delete`, the JSON body otherwise), and decoded bodies come back:
37
+
38
+ ``` python
39
+ cli = HttpCli('https://jsonplaceholder.typicode.com')
40
+ cli.get('todos/1')
41
+ ```
42
+
43
+ ``` python
44
+ cli.post('posts', title='hi')
45
+ ```
46
+
47
+ [`AsyncHttpCli`](https://AnswerDotAI.github.io/fasttransport/core.html#asynchttpcli) is the async twin. Its verbs return awaitables:
48
+
49
+ ``` python
50
+ acli = AsyncHttpCli('https://jsonplaceholder.typicode.com')
51
+ await acli.get('todos/1')
52
+ ```
53
+
54
+ The [core page](https://AnswerDotAI.github.io/fasttransport/core.html) documents the rest with runnable examples: SSE streaming, error enrichment, multipart uploads, and managing your own client.
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
@@ -0,0 +1,42 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/fasttransport',
5
+ 'doc_host': 'https://AnswerDotAI.github.io',
6
+ 'git_url': 'https://github.com/AnswerDotAI/fasttransport',
7
+ 'lib_path': 'fasttransport'},
8
+ 'syms': { 'fasttransport.core': { 'fasttransport.core.AsyncHttpCli': ('core.html#asynchttpcli', 'fasttransport/core.py'),
9
+ 'fasttransport.core.AsyncHttpCli._req': ('core.html#asynchttpcli._req', 'fasttransport/core.py'),
10
+ 'fasttransport.core.AsyncTransport': ('core.html#asynctransport', 'fasttransport/core.py'),
11
+ 'fasttransport.core.AsyncTransport.__init__': ( 'core.html#asynctransport.__init__',
12
+ 'fasttransport/core.py'),
13
+ 'fasttransport.core.AsyncTransport._client': ( 'core.html#asynctransport._client',
14
+ 'fasttransport/core.py'),
15
+ 'fasttransport.core.AsyncTransport._decode': ( 'core.html#asynctransport._decode',
16
+ 'fasttransport/core.py'),
17
+ 'fasttransport.core.AsyncTransport._headers': ( 'core.html#asynctransport._headers',
18
+ 'fasttransport/core.py'),
19
+ 'fasttransport.core.AsyncTransport._request_headers': ( 'core.html#asynctransport._request_headers',
20
+ 'fasttransport/core.py'),
21
+ 'fasttransport.core.AsyncTransport.aclose': ( 'core.html#asynctransport.aclose',
22
+ 'fasttransport/core.py'),
23
+ 'fasttransport.core.AsyncTransport.request': ( 'core.html#asynctransport.request',
24
+ 'fasttransport/core.py'),
25
+ 'fasttransport.core.AsyncTransport.stream': ( 'core.html#asynctransport.stream',
26
+ 'fasttransport/core.py'),
27
+ 'fasttransport.core.HttpCli': ('core.html#httpcli', 'fasttransport/core.py'),
28
+ 'fasttransport.core.HttpCli.__dir__': ('core.html#httpcli.__dir__', 'fasttransport/core.py'),
29
+ 'fasttransport.core.HttpCli.__getattr__': ('core.html#httpcli.__getattr__', 'fasttransport/core.py'),
30
+ 'fasttransport.core.HttpCli.__init__': ('core.html#httpcli.__init__', 'fasttransport/core.py'),
31
+ 'fasttransport.core.HttpCli._req': ('core.html#httpcli._req', 'fasttransport/core.py'),
32
+ 'fasttransport.core.HttpCli._url': ('core.html#httpcli._url', 'fasttransport/core.py'),
33
+ 'fasttransport.core.HttpCli.body': ('core.html#httpcli.body', 'fasttransport/core.py'),
34
+ 'fasttransport.core.ProtocolError': ('core.html#protocolerror', 'fasttransport/core.py'),
35
+ 'fasttransport.core.SyncTransport': ('core.html#synctransport', 'fasttransport/core.py'),
36
+ 'fasttransport.core.SyncTransport._client': ( 'core.html#synctransport._client',
37
+ 'fasttransport/core.py'),
38
+ 'fasttransport.core.SyncTransport.close': ('core.html#synctransport.close', 'fasttransport/core.py'),
39
+ 'fasttransport.core.SyncTransport.request': ( 'core.html#synctransport.request',
40
+ 'fasttransport/core.py'),
41
+ 'fasttransport.core.SyncTransport.stream': ( 'core.html#synctransport.stream',
42
+ 'fasttransport/core.py')}}}
@@ -0,0 +1,138 @@
1
+ """Sync and async HTTP transports over httpx2, and base classes for small REST clients
2
+
3
+ Docs: https://AnswerDotAI.github.io/fasttransport/core.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['ProtocolError', 'AsyncTransport', 'SyncTransport', 'HttpCli', 'AsyncHttpCli']
9
+
10
+ # %% ../nbs/00_core.ipynb #ca352892
11
+ from fastcore.meta import delegates
12
+ import httpx2, json as jsonlib
13
+ from functools import partial
14
+ from contextlib import nullcontext
15
+ from httpx2 import EventSource
16
+
17
+ # %% ../nbs/00_core.ipynb #09ff28d5
18
+ class ProtocolError(Exception):
19
+ "Raised when a stream payload does not match the expected protocol shape."
20
+
21
+ # %% ../nbs/00_core.ipynb #a3a6efd9
22
+ class AsyncTransport:
23
+ "Thin async transport over httpx2. By default each request gets a fresh client, so nothing is tied to an event loop; pass `client=` to use a persistent client that you manage (and close via `aclose`)."
24
+ def __init__(self, *, timeout=60.0, client=None, base_headers=None, follow_redirects=True, verify=True):
25
+ self.timeout,self.client,self.base_headers,self.follow_redirects,self.verify = timeout,client,base_headers or {},follow_redirects,verify
26
+
27
+ def _client(self):
28
+ if self.client: return nullcontext(self.client)
29
+ return httpx2.AsyncClient(timeout=self.timeout, follow_redirects=self.follow_redirects, verify=self.verify)
30
+
31
+ async def aclose(self):
32
+ if self.client: await self.client.aclose()
33
+
34
+ def _headers(self, headers=None): return {**self.base_headers, **(headers or {})}
35
+
36
+ def _request_headers(self, headers=None, *, files=None):
37
+ "Merge headers and drop explicit content-type for multipart uploads."
38
+ h = self._headers(headers)
39
+ if files is not None:
40
+ # Let httpx compute multipart/form-data with boundary.
41
+ for k in list(h):
42
+ if k.lower() == "content-type": h.pop(k, None)
43
+ return h
44
+
45
+ @staticmethod
46
+ def _decode(resp):
47
+ "Decode response body using content type."
48
+ if not resp.content: return None
49
+ ctype = (resp.headers.get("content-type") or "").lower()
50
+ if "application/json" in ctype or ctype.endswith("+json"): return resp.json()
51
+ if ctype.startswith("text/") or "application/x-ndjson" in ctype: return resp.text
52
+ return resp.content
53
+
54
+ async def request(self, method, url, *, headers=None, params=None, json=None, data=None,
55
+ files=None, content=None, raw=False):
56
+ "Execute a request and decode JSON/text/binary response."
57
+ async with self._client() as client:
58
+ resp = await client.request(method, url, headers=self._request_headers(headers, files=files),
59
+ params=params, json=json, data=data, files=files, content=content)
60
+ try: resp.raise_for_status()
61
+ except httpx2.HTTPStatusError as e:
62
+ e.args = (f"{e}\n{resp.text}",)
63
+ raise
64
+ return resp if raw else self._decode(resp)
65
+
66
+ async def stream(self, method, url, *, headers=None, params=None, json=None, data=None, files=None):
67
+ async with self._client() as client:
68
+ async with client.stream(method, url, headers=self._request_headers(headers, files=files),
69
+ params=params, json=json, data=data, files=files) as resp:
70
+ try: resp.raise_for_status()
71
+ except httpx2.HTTPStatusError as e:
72
+ try: await resp.aread()
73
+ except Exception: pass
74
+ e.args = (f"{e}\n{resp.text}",)
75
+ raise
76
+ if 'content-type' not in resp.headers: resp.headers['content-type'] = 'text/event-stream' # some backends (codex) omit it; the old parser never checked
77
+ events = aiter(EventSource(resp, max_event_size=None))
78
+ try:
79
+ async for event in events:
80
+ if not event.data: continue
81
+ if event.data == "[DONE]": return
82
+ try: raw = jsonlib.loads(event.data)
83
+ except jsonlib.JSONDecodeError as e: raise ProtocolError(f"Invalid SSE JSON: {e}") from e
84
+ if isinstance(raw, dict): yield raw
85
+ else: raise ProtocolError(f"Expected SSE JSON object, got {type(raw).__name__}")
86
+ finally: await events.aclose()
87
+
88
+ # %% ../nbs/00_core.ipynb #4df92440
89
+ class SyncTransport(AsyncTransport):
90
+ "Sync twin of `AsyncTransport`, over `httpx2.Client`. SSE needs the async transport, so `stream` raises."
91
+ def stream(self, *args, **kwargs):
92
+ raise TypeError("SSE streaming needs `AsyncTransport`; drive it from sync code with `fastcore.aio.iter_sync`")
93
+
94
+ def _client(self):
95
+ if self.client: return nullcontext(self.client)
96
+ return httpx2.Client(timeout=self.timeout, follow_redirects=self.follow_redirects, verify=self.verify)
97
+
98
+ def close(self):
99
+ if self.client: self.client.close()
100
+
101
+ def request(self, method, url, *, headers=None, params=None, json=None, data=None,
102
+ files=None, content=None, raw=False):
103
+ "Sync version of `AsyncTransport.request`."
104
+ with self._client() as client:
105
+ resp = client.request(method, url, headers=self._request_headers(headers, files=files),
106
+ params=params, json=json, data=data, files=files, content=content)
107
+ try: resp.raise_for_status()
108
+ except httpx2.HTTPStatusError as e:
109
+ e.args = (f"{e}\n{resp.text}",)
110
+ raise
111
+ return resp if raw else self._decode(resp)
112
+
113
+ # %% ../nbs/00_core.ipynb #4e549f4c
114
+ class HttpCli:
115
+ "Small REST client over `SyncTransport`: verb attributes (`get`, `post`, `put`, `patch`, `delete`) call `body`, with kwargs as the payload"
116
+ tcls = SyncTransport
117
+ _verbs = ('get','post','put','patch','delete')
118
+ @delegates(SyncTransport)
119
+ def __init__(self, base_url, transport=None, **kwargs):
120
+ self.base_url = base_url.rstrip('/')
121
+ self.transport = transport or self.tcls(**kwargs)
122
+
123
+ def _url(self, path): return f"{self.base_url}/{str(path).lstrip('/')}" if path else self.base_url
124
+ def _req(self, method, path='', **kw): return self.transport.request(method, self._url(path), **kw)
125
+ def body(self, method, path='', /, params=None, json=None, useparams_=False, **kw):
126
+ "Send a request with `kw` merged into `params` if `useparams_`, else into `json`"
127
+ if useparams_: params = {**(params or {}), **kw}
128
+ else: json = {**(json or {}), **kw}
129
+ return self._req(method, path, params=params, json=json or None)
130
+ def __getattr__(self, name):
131
+ if name not in self._verbs: raise AttributeError(name)
132
+ return partial(self.body, name.upper(), useparams_=name in ('get','delete'))
133
+ def __dir__(self): return [*super().__dir__(), *self._verbs]
134
+
135
+ class AsyncHttpCli(HttpCli):
136
+ "Async twin of `HttpCli`, over `AsyncTransport`: the verbs return awaitables"
137
+ tcls = AsyncTransport
138
+ async def _req(self, method, path='', **kw): return await self.transport.request(method, self._url(path), **kw)
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: fasttransport
3
+ Version: 0.0.1
4
+ Summary: Sync and async HTTP transports over httpx2, plus base classes for small REST clients
5
+ Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/AnswerDotAI/fasttransport
8
+ Project-URL: Documentation, https://AnswerDotAI.github.io/fasttransport/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: fastcore>=2.2.11
16
+ Requires-Dist: httpx2>=2.9.1
17
+ Provides-Extra: dev
18
+ Requires-Dist: cachy>=0.0.7; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # fasttransport
22
+
23
+
24
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
25
+
26
+ ## Install
27
+
28
+ ``` sh
29
+ pip install fasttransport
30
+ ```
31
+
32
+ ## Why
33
+
34
+ Every small API wrapper needs the same plumbing: headers merged into each request, responses decoded by content type, errors that carry the response body, and SSE parsing for streams. Most wrappers also repeat the same mistake. They create one httpx client at startup and keep it, which pins its pooled connections to the event loop that created them. Code that later runs under a different loop, common in tests and background tasks, then fails with confusing connection errors.
35
+
36
+ fasttransport is that plumbing written once, on [httpx2](https://github.com/pydantic/httpx2). Each request gets a fresh client and nothing is tied to a loop. Pass `client=` to manage a persistent client yourself. [fastspec](https://github.com/AnswerDotAI/fastspec) builds its spec-driven clients on these transports, [ghapi](https://github.com/AnswerDotAI/ghapi) its GitHub client, and [solveit](https://github.com/AnswerDotAI/solveit) its gateway clients.
37
+
38
+ ## Get started
39
+
40
+ [`SyncTransport.request`](https://AnswerDotAI.github.io/fasttransport/core.html#synctransport.request) executes a call and returns the decoded body: JSON arrives as a dict, text as text, and anything else as bytes. HTTP errors raise with the response body included in the message.
41
+
42
+ ``` python
43
+ from fasttransport.core import *
44
+ ```
45
+
46
+ ``` python
47
+ SyncTransport().request('GET', 'https://jsonplaceholder.typicode.com/todos/1')
48
+ ```
49
+
50
+ [`AsyncTransport`](https://AnswerDotAI.github.io/fasttransport/core.html#asynctransport) is the same, awaited. It also has `stream`, an async generator that parses SSE events into JSON dicts. The [core page](https://AnswerDotAI.github.io/fasttransport/core.html) streams a chat completion with it.
51
+
52
+ ``` python
53
+ await AsyncTransport().request('GET', 'https://jsonplaceholder.typicode.com/users/1')
54
+ ```
55
+
56
+ A small REST client is a base URL plus verbs. [`HttpCli`](https://AnswerDotAI.github.io/fasttransport/core.html#httpcli) verbs take a path relative to the base, kwargs become the payload (query params on `get` and `delete`, the JSON body otherwise), and decoded bodies come back:
57
+
58
+ ``` python
59
+ cli = HttpCli('https://jsonplaceholder.typicode.com')
60
+ cli.get('todos/1')
61
+ ```
62
+
63
+ ``` python
64
+ cli.post('posts', title='hi')
65
+ ```
66
+
67
+ [`AsyncHttpCli`](https://AnswerDotAI.github.io/fasttransport/core.html#asynchttpcli) is the async twin. Its verbs return awaitables:
68
+
69
+ ``` python
70
+ acli = AsyncHttpCli('https://jsonplaceholder.typicode.com')
71
+ await acli.get('todos/1')
72
+ ```
73
+
74
+ The [core page](https://AnswerDotAI.github.io/fasttransport/core.html) documents the rest with runnable examples: SSE streaming, error enrichment, multipart uploads, and managing your own client.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ fasttransport/__init__.py
6
+ fasttransport/_modidx.py
7
+ fasttransport/core.py
8
+ fasttransport.egg-info/PKG-INFO
9
+ fasttransport.egg-info/SOURCES.txt
10
+ fasttransport.egg-info/dependency_links.txt
11
+ fasttransport.egg-info/entry_points.txt
12
+ fasttransport.egg-info/requires.txt
13
+ fasttransport.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ fasttransport = fasttransport._modidx:d
@@ -0,0 +1,5 @@
1
+ fastcore>=2.2.11
2
+ httpx2>=2.9.1
3
+
4
+ [dev]
5
+ cachy>=0.0.7
@@ -0,0 +1 @@
1
+ fasttransport
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "fasttransport"
7
+ dynamic = ["version"]
8
+ description = "Sync and async HTTP transports over httpx2, plus base classes for small REST clients"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [{name = "Jeremy Howard", email = "github@jhoward.fastmail.fm"}]
13
+ keywords = ['nbdev']
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ ]
18
+ dependencies = ['fastcore>=2.2.11', 'httpx2>=2.9.1']
19
+
20
+ [project.optional-dependencies]
21
+ dev = ['cachy>=0.0.7']
22
+
23
+ [project.urls]
24
+ Repository = "https://github.com/AnswerDotAI/fasttransport"
25
+ Documentation = "https://AnswerDotAI.github.io/fasttransport/"
26
+
27
+ [project.entry-points.nbdev]
28
+ fasttransport = "fasttransport._modidx:d"
29
+
30
+ [tool.setuptools.dynamic]
31
+ version = {attr = "fasttransport.__version__"}
32
+
33
+ [tool.setuptools.packages.find]
34
+ include = ["fasttransport"]
35
+
36
+ [tool.nbdev]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+