rusty-req 0.4.18__cp39-abi3-win_amd64.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 rusty-req might be problematic. Click here for more details.

rusty_req/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from .rusty_req import *
2
+
3
+ __doc__ = rusty_req.__doc__
4
+ if hasattr(rusty_req, "__all__"):
5
+ __all__ = rusty_req.__all__
Binary file
@@ -0,0 +1,441 @@
1
+ Metadata-Version: 2.4
2
+ Name: rusty-req
3
+ Version: 0.4.18
4
+ Classifier: Programming Language :: Python
5
+ Classifier: Programming Language :: Python :: 3
6
+ Classifier: Programming Language :: Rust
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: OS Independent
9
+ Summary: ⚑ High-performance async HTTP client in Rust with Python bindings for blazing-fast batch requests.
10
+ Author-email: KAY53N <kaysen820@gmail.com>
11
+ License: MIT
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
+ Project-URL: Homepage, https://github.com/KAY53N/rusty-req
15
+ Project-URL: Repository, https://github.com/KAY53N/rusty-req
16
+ Project-URL: Bug Tracker, https://github.com/KAY53N/rusty-req/issues
17
+ Project-URL: Documentation, https://github.com/KAY53N/rusty-req#readme
18
+
19
+ # rusty-req
20
+
21
+ [![PyPI Version](https://img.shields.io/pypi/v/rusty-req)](https://pypi.org/project/rusty-req/)
22
+ [![GitHub Downloads](https://img.shields.io/github/downloads/KAY53N/rusty-req/total)](https://github.com/KAY53N/rusty-req/releases)
23
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
24
+
25
+ A high-performance asynchronous request library based on Rust and Python, suitable for scenarios that require high-throughput concurrent HTTP requests. It implements the core concurrent logic in Rust and packages it into a Python module using [PyO3](https://pyo3.rs/) and [maturin](https://github.com/PyO3/maturin), combining Rust's performance with Python's ease of use.
26
+
27
+ ---
28
+
29
+ ### 🌐 [English](README.md) | [δΈ­ζ–‡](README.zh.md)
30
+
31
+ ## πŸš€ Features
32
+
33
+ - **Dual Request Modes**: Supports both batch concurrent requests (`fetch_requests`) and single asynchronous requests (`fetch_single`).
34
+ - **High Performance**: Built with Rust, Tokio, and a shared `reqwest` client for maximum throughput.
35
+ - **Highly Customizable**: Allows custom headers, parameters/body, per-request timeouts, and tags.
36
+ - **Flexible Concurrency Modes**: Choose between `SELECT_ALL` (default, get results as they complete) and `JOIN_ALL` (wait for all requests to finish) to fit your use case.
37
+ - **Smart Response Handling**: Automatically decompresses `gzip`, `brotli`, and `deflate` encoded responses.
38
+ - **Global Timeout Control**: Use `total_timeout` in batch requests to prevent hangs.
39
+ - **Detailed Results**: Each response includes the HTTP status, body, metadata (like processing time), and any exceptions.
40
+ - **Debug Mode**: An optional debug mode (`set_debug(True)`) prints detailed request/response information.
41
+
42
+ ## πŸ”§ Installation
43
+
44
+ ```bash
45
+ pip install rusty-req
46
+ ```
47
+ Or build from source:
48
+ ```
49
+ # This will compile the Rust code and create a .whl file
50
+ maturin build --release
51
+
52
+ # Install from the generated wheel
53
+ pip install target/wheels/rusty_req-*.whl
54
+ ```
55
+
56
+ ## Development & Debugging
57
+ ```
58
+ cargo watch -s "maturin develop"
59
+ ```
60
+
61
+ ## βš™οΈ Proxy Configuration & Debug
62
+
63
+ ### 1. Using Proxy
64
+
65
+ If you need to access external networks through a proxy, create a `ProxyConfig` object and set it as a global proxy:
66
+
67
+ ```python
68
+ import asyncio
69
+ import rusty_req
70
+
71
+ async def proxy_example():
72
+ # Create ProxyConfig object
73
+ proxy = rusty_req.ProxyConfig(
74
+ http="http://127.0.0.1:7890",
75
+ https="http://127.0.0.1:7890"
76
+ )
77
+
78
+ # Set global proxy (all requests will use this proxy)
79
+ await rusty_req.set_global_proxy(proxy)
80
+
81
+ # Send request (will go through proxy automatically)
82
+ resp = await rusty_req.fetch_single(url="https://httpbin.org/get")
83
+ print(resp)
84
+
85
+ if __name__ == "__main__":
86
+ asyncio.run(proxy_example())
87
+ ```
88
+
89
+ ### 2. Debug Logging
90
+
91
+ `set_debug` enables debug mode, supporting **console output** and **log file writing**:
92
+
93
+ ```python
94
+ import rusty_req
95
+
96
+ # Print debug logs to console only
97
+ rusty_req.set_debug(True)
98
+
99
+ # Print to console and write to log file
100
+ rusty_req.set_debug(True, "logs/debug.log")
101
+
102
+ # Disable debug mode
103
+ rusty_req.set_debug(False)
104
+ ```
105
+
106
+ ## πŸ“¦ Example Usage
107
+ ### 1. Fetching a Single Request (`fetch_single`)
108
+ Perfect for making a single asynchronous call and awaiting its result.
109
+
110
+ ```python
111
+ import asyncio
112
+ import pprint
113
+ import rusty_req
114
+
115
+ async def single_request_example():
116
+ """Demonstrates how to use fetch_single for a POST request."""
117
+ print("πŸš€ Fetching a single POST request to httpbin.org...")
118
+
119
+ # Enable debug mode to see detailed logs in the console
120
+ rusty_req.set_debug(True)
121
+
122
+ response = await rusty_req.fetch_single(
123
+ url="https://httpbin.org/post",
124
+ method="POST",
125
+ params={"user_id": 123, "source": "example"},
126
+ headers={"X-Client-Version": "1.0"},
127
+ tag="my-single-post"
128
+ )
129
+
130
+ print("\nβœ… Request finished. Response:")
131
+ pprint.pprint(response)
132
+
133
+ if __name__ == "__main__":
134
+ asyncio.run(single_request_example())
135
+ ```
136
+
137
+ ### 2. Fetching Batch Requests (`fetch_requests`)
138
+
139
+ The core feature for handling a large number of requests concurrently. This example simulates a simple load test.
140
+ ```python
141
+ import asyncio
142
+ import time
143
+ import rusty_req
144
+ from rusty_req import ConcurrencyMode
145
+
146
+ async def batch_requests_example():
147
+ """Demonstrates 100 concurrent requests with a global timeout."""
148
+ requests = [
149
+ rusty_req.RequestItem(
150
+ url="https://httpbin.org/delay/2", # This endpoint waits 2 seconds
151
+ method="GET",
152
+ timeout=2.9, # Per-request timeout, should succeed
153
+ tag=f"test-req-{i}",
154
+ )
155
+ for i in range(100)
156
+ ]
157
+
158
+ # Disable debug logs for cleaner output
159
+ rusty_req.set_debug(False)
160
+
161
+ print("πŸš€ Starting 100 concurrent requests...")
162
+ start_time = time.perf_counter()
163
+
164
+ # Set a global timeout of 3.0 seconds. Some requests will be cut off.
165
+ responses = await rusty_req.fetch_requests(
166
+ requests,
167
+ total_timeout=3.0,
168
+ mode=ConcurrencyMode.SELECT_ALL # Explicitly use SELECT_ALL mode
169
+ )
170
+
171
+ total_time = time.perf_counter() - start_time
172
+
173
+ # --- Process results ---
174
+ success_count = 0
175
+ failed_count = 0
176
+ for r in responses:
177
+ # Check the 'exception' field to see if the request was successful
178
+ if r.get("exception") and r["exception"].get("type"):
179
+ failed_count += 1
180
+ else:
181
+ success_count += 1
182
+
183
+ print("\nπŸ“Š Load Test Summary:")
184
+ print(f"⏱️ Total time taken: {total_time:.2f}s")
185
+ print(f"βœ… Successful requests: {success_count}")
186
+ print(f"⚠️ Failed or timed-out requests: {failed_count}")
187
+
188
+ if __name__ == "__main__":
189
+ asyncio.run(batch_requests_example())
190
+ ```
191
+
192
+ ### 3. Understanding Concurrency Modes (`SELECT_ALL` vs `JOIN_ALL`)
193
+
194
+ The `fetch_requests` function supports two powerful concurrency strategies. Choosing the right one is key to building robust applications.
195
+
196
+ - **`ConcurrencyMode.SELECT_ALL` (Default): Best-Effort Collector**
197
+ This mode operates on a "first come, first served" or "best-effort" basis. It aims to collect as many successful results as possible within the given `total_timeout`.
198
+ - It returns results as soon as they complete.
199
+ - If the `total_timeout` is reached, it gracefully returns all the requests that have already succeeded, while marking any still-pending requests as timed out.
200
+ - **A failure in one request does not affect others.**
201
+
202
+ - **`ConcurrencyMode.JOIN_ALL`: Transactional (All-or-Nothing)**
203
+ This mode treats the entire batch of requests as a single, atomic transaction. It is much stricter.
204
+ - It waits for **all** submitted requests to complete first.
205
+ - It then inspects the results.
206
+ - **Success Case**: Only if *every single request was successful* will it return the complete list of successful results.
207
+ - **Failure Case**: If *even one request fails* for any reason (e.g., its individual timeout, a network error, or a non-2xx status code), this mode will discard all results and return a list where **every request is marked as a global failure.**
208
+
209
+ ### 4. Timeout Performance Comparison
210
+
211
+ Under the same test conditions (global timeout 3s, per-request timeout 2.6s, httpbin delay 2.3s), we compared the performance of different libraries:
212
+
213
+ | Library / Framework | Total Requests | Successful | Timed Out | Success Rate | Actual Total Time | Notes / Description |
214
+ |--------------------|----------------|------------|-----------|--------------|-------------------|-------------------|
215
+ | **Rusty-req** | 1000 | 1000 | 0 | 100.0% | 2.56s | Stable performance under high concurrency; precise control of per-request and total timeouts |
216
+ | **httpx** | 1000 | 0 | 0 | 0.0% | 26.77s | Timeout parameters did not take effect; overall performance abnormal |
217
+ | **aiohttp** | 1000 | 100 | 900 | 10.0% | 2.66s | Per-request timeout effective, but global timeout control insufficient |
218
+ | **requests** | 1000 | 1000 | 0 | 100.0% | 3.45s | Synchronous blocking mode; not suitable for large-scale concurrent requests |
219
+
220
+ Key takeaways:
221
+ - **Rusty-req** can complete tasks within strict global timeout limits while maintaining high concurrency and stability.
222
+ - Traditional asynchronous libraries struggle with global timeout enforcement and extreme concurrency scenarios.
223
+ - Synchronous libraries like `requests` produce correct results but are not scalable for large-scale concurrent requests.
224
+
225
+ ![Timeout Performance Comparison](https://raw.githubusercontent.com/KAY53N/rusty-req/main/docs/images/timeout_performance_comparison.png)
226
+
227
+ ---
228
+
229
+ ### Quick Comparison
230
+
231
+ | Aspect | `ConcurrencyMode.SELECT_ALL` (Default) | `ConcurrencyMode.JOIN_ALL` |
232
+ | :-------------------- | :------------------------------------------------------------------- | :------------------------------------------------------------------ |
233
+ | **Failure Handling** | **Tolerant**. One failure does not affect other successful requests. | **Strict / Atomic**. One failure causes the entire batch to fail. |
234
+ | **Primary Use Case** | Maximizing throughput; getting as much data as possible. | Tasks that must succeed or fail as a single unit (e.g., transactions). |
235
+ | **Result Order** | By completion time (fastest first). | By original submission order. |
236
+ | **"When do I get results?"** | As they complete, one by one. | All at once, only after every request has finished and been validated. |
237
+
238
+ ---
239
+
240
+ ### Code Example
241
+
242
+ The example below clearly demonstrates the difference in behavior.
243
+
244
+ ```python
245
+ import asyncio
246
+ import rusty_req
247
+ from rusty_req import ConcurrencyMode
248
+
249
+ async def concurrency_modes_example():
250
+ """Demonstrates the difference between SELECT_ALL and JOIN_ALL modes."""
251
+ # Note: We are using an endpoint that returns 500 to force a failure.
252
+ requests = [
253
+ rusty_req.RequestItem(url="https://httpbin.org/delay/2", tag="should_succeed"),
254
+ rusty_req.RequestItem(url="https://httpbin.org/status/500", tag="will_fail"),
255
+ rusty_req.RequestItem(url="https://httpbin.org/delay/1", tag="should_also_succeed"),
256
+ ]
257
+
258
+ # --- 1. Test SELECT_ALL ---
259
+ print("--- πŸš€ Testing SELECT_ALL (Best-Effort) ---")
260
+ results_select = await rusty_req.fetch_requests(
261
+ requests,
262
+ mode=ConcurrencyMode.SELECT_ALL,
263
+ total_timeout=3.0
264
+ )
265
+
266
+ print("Results:")
267
+ for res in results_select:
268
+ tag = res.get("meta", {}).get("tag")
269
+ status = res.get("http_status")
270
+ err_type = res.get("exception", {}).get("type")
271
+ print(f" - Tag: {tag}, Status: {status}, Exception: {err_type}")
272
+
273
+ print("\n" + "="*50 + "\n")
274
+
275
+ # --- 2. Test JOIN_ALL ---
276
+ print("--- πŸš€ Testing JOIN_ALL (All-or-Nothing) ---")
277
+ results_join = await rusty_req.fetch_requests(
278
+ requests,
279
+ mode=ConcurrencyMode.JOIN_ALL,
280
+ total_timeout=3.0
281
+ )
282
+
283
+ print("Results:")
284
+ for res in results_join:
285
+ tag = res.get("meta", {}).get("tag")
286
+ status = res.get("http_status")
287
+ err_type = res.get("exception", {}).get("type")
288
+ print(f" - Tag: {tag}, Status: {status}, Exception: {err_type}")
289
+
290
+ if __name__ == "__main__":
291
+ asyncio.run(concurrency_modes_example())
292
+ ```
293
+ The expected output from the script above:
294
+
295
+ ```
296
+ --- πŸš€ Testing SELECT_ALL (Best-Effort) ---
297
+ Results:
298
+ - Tag: should_also_succeed, Status: 200, Exception: None
299
+ - Tag: will_fail, Status: 500, Exception: HttpStatusError
300
+ - Tag: should_succeed, Status: 200, Exception: None
301
+
302
+ ==================================================
303
+
304
+ --- πŸš€ Testing JOIN_ALL (All-or-Nothing) ---
305
+ Results:
306
+ - Tag: should_succeed, Status: 0, Exception: GlobalTimeout
307
+ - Tag: will_fail, Status: 0, Exception: GlobalTimeout
308
+ - Tag: should_also_succeed, Status: 0, Exception: GlobalTimeout
309
+ ```
310
+
311
+ ## 🧱 Data Structures
312
+
313
+ ### `RequestItem` Parameters
314
+
315
+ | Field | Type | Required | Description |
316
+ |:------------------|:----------------|:--------:|:-----------------------------------------------------------------------------------------------------------------------------------------------|
317
+ | `url` | `str` | βœ… | The target URL. |
318
+ | `method` | `str` | βœ… | The HTTP method. |
319
+ | `params` | `dict` / `None` | No | For GET/DELETE, converted to URL query parameters. For POST/PUT/PATCH, sent as a JSON body. |
320
+ | `headers` | `dict` / `None` | No | Custom HTTP headers. |
321
+ | `tag` | `str` | No | An arbitrary tag to help identify or index the response. |
322
+ | `http_version` | `str` | No | The default behavior when the HTTP version is set to β€œAuto” is to attempt HTTP/2 first, and fall back to HTTP/1.1 if HTTP/2 is not supported. |
323
+ | `ssl_verify` | `bool` | No | **SSL certificate verification** (default `True`, set `False` to disable for self-signed certificates) |
324
+ | `timeout` | `float` | βœ… | Timeout for this individual request in seconds. Defaults to 30s. |
325
+
326
+ ---
327
+
328
+ ### `ProxyConfig` Parameters
329
+
330
+ | Field | Type | Required | Description |
331
+ |:------------|:---------------------|:--------:|:----------------------------------------------------------------------------|
332
+ | `http` | `str` / `None` | No | Proxy URL for HTTP requests (e.g. `http://127.0.0.1:8080`). |
333
+ | `https` | `str` / `None` | No | Proxy URL for HTTPS requests. |
334
+ | `all` | `str` / `None` | No | A single proxy URL applied to all schemes (overrides `http`/`https`). |
335
+ | `no_proxy` | `List[str]` / `None` | No | List of hostnames/IPs to exclude from proxying. |
336
+ | `username` | `str` / `None` | No | Optional proxy authentication username. |
337
+ | `password` | `str` / `None` | No | Optional proxy authentication password. |
338
+ | `trust_env` | `bool` / `None` | No | Whether to respect system environment variables (`HTTP_PROXY`, `NO_PROXY`). |
339
+
340
+ ---
341
+
342
+ ### `fetch_requests` Parameters
343
+
344
+ | Field | Type | Required | Description |
345
+ | :-------------- | :-------------------- | :------: | :------------------------------------------------------------------------------------------------------ |
346
+ | `requests` | `List[RequestItem]` | βœ… | A list of `RequestItem` objects to be executed concurrently. |
347
+ | `total_timeout` | `float` | No | A global timeout in seconds for the entire batch operation. |
348
+ | `mode` | `ConcurrencyMode` | No | The concurrency strategy. `SELECT_ALL` (default) for best-effort collection. `JOIN_ALL` for atomic (all-or-nothing) execution. See Section 3 for a detailed comparison.|
349
+
350
+ ---
351
+
352
+ ### `fetch_single` Parameters
353
+
354
+ | Field | Type | Required | Description |
355
+ |:--------------|:--------------------|:--------:|:----------------------------------------------------------------------------------------------------------------|
356
+ | `url` | `str` | βœ… | The target request URL. |
357
+ | `method` | `str` / `None` | No | HTTP method, e.g., `"GET"`, `"POST"`. If not provided, the client may handle defaults. |
358
+ | `params` | `dict` / `None` | No | Request parameters. For GET/DELETE, converted to URL query parameters; for POST/PUT/PATCH, sent as JSON body. |
359
+ | `timeout` | `float` / `None` | No | Timeout for this request in seconds. Defaults to 30s. |
360
+ | `headers` | `dict` / `None` | No | Custom HTTP request headers. |
361
+ | `tag` | `str` / `None` | No | Arbitrary tag to help identify or index the response. |
362
+ | `proxy` | `ProxyConfig` / `None` | No | Optional proxy configuration. Applied to this request if provided. |
363
+ | `http_version`| `HttpVersion` / `None` | No | HTTP version choice, usually supports `"Auto"` (try HTTP/2, fallback to HTTP/1.1), `"1.1"`, `"2"`, etc. |
364
+ | `ssl_verify` | `bool` / `None` | No | Whether to verify SSL certificates. Defaults to `True`; set `False` to ignore self-signed certificates. |
365
+
366
+ ---
367
+
368
+ ### Response Dictionary Format
369
+
370
+ Both `fetch_single` and `fetch_requests` return a dictionary (or a list of dictionaries) with a consistent structure.
371
+
372
+ #### Example of a successful response:
373
+
374
+ ```json
375
+ {
376
+ "http_status": 200,
377
+ "response": {
378
+ "headers": {
379
+ "access-control-allow-credentials": "true",
380
+ "access-control-allow-origin": "*",
381
+ "connection": "keep-alive",
382
+ "content-length": "314",
383
+ "content-type": "application/json",
384
+ "date": "Wed, 10 Sep 2025 03:15:31 GMT",
385
+ "server": "gunicorn/19.9.0"
386
+ },
387
+ "content": "{\"data\":\"...\", \"headers\":{\"...\"}}"
388
+ },
389
+ "meta": {
390
+ "process_time": "2.0846",
391
+ "request_time": "2025-09-10 11:22:46 -> 2025-09-10 11:22:48",
392
+ "tag": "req-0"
393
+ },
394
+ "exception": {}
395
+ }
396
+ ```
397
+
398
+ #### Example of a failed response (e.g., timeout):
399
+ ```json
400
+ {
401
+ "http_status": 0,
402
+ "response": {
403
+ "headers": {
404
+ "access-control-allow-credentials": "true",
405
+ "access-control-allow-origin": "*",
406
+ "connection": "keep-alive",
407
+ "content-length": "314",
408
+ "content-type": "application/json",
409
+ "date": "Wed, 10 Sep 2025 03:15:31 GMT",
410
+ "server": "gunicorn/19.9.0"
411
+ },
412
+ "content": ""
413
+ },
414
+ "meta": {
415
+ "process_time": "3.0012",
416
+ "request_time": "2025-08-08 03:15:05 -> 2025-08-08 03:15:08",
417
+ "tag": "test-req-50"
418
+ },
419
+ "exception": {
420
+ "type": "Timeout",
421
+ "message": "Request timeout after 3.00 seconds"
422
+ }
423
+ }
424
+ ```
425
+
426
+ ## Changelog
427
+
428
+ For a detailed list of changes, see the [CHANGELOG](CHANGELOG.md)
429
+
430
+ ---
431
+
432
+ ### &#8627; Stargazers
433
+ [![Stargazers repo roster for @KAY53N/rusty-req](https://reporoster.com/stars/KAY53N/rusty-req)](https://github.com/KAY53N/rusty-req/stargazers)
434
+
435
+ ### &#8627; Forkers
436
+ [![Forkers repo roster for @KAY53N/rusty-req](https://reporoster.com/forks/KAY53N/rusty-req)](https://github.com/KAY53N/rusty-req/network/members)
437
+
438
+
439
+ ## πŸ“„ License
440
+ This project is licensed under the [MIT License](https://opensource.org/license/MIT).
441
+
@@ -0,0 +1,5 @@
1
+ rusty_req-0.4.18.dist-info/METADATA,sha256=fLpewgc0xDjnJlE8uMJqbNVklcTYh2lDMom8Qchqnzk,21268
2
+ rusty_req-0.4.18.dist-info/WHEEL,sha256=KP1XRbQ7GUOK0PLztcv6rn22fh7mfz6y3ftv90H-6z4,94
3
+ rusty_req/__init__.py,sha256=XfQUTvk1FFMD7UyS817WUsedia2I8IeuvVba4QktOX0,119
4
+ rusty_req/rusty_req.pyd,sha256=zMqMzkZB8nQWaSMHv38U8eV4-lbc37FbJC8r8XpUTgY,4185600
5
+ rusty_req-0.4.18.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: maturin (1.9.2)
3
+ Root-Is-Purelib: false
4
+ Tag: cp39-abi3-win_amd64