rnet 3.0.0rc2__cp311-abi3-win32.whl → 3.0.0rc4__cp311-abi3-win32.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 rnet might be problematic. Click here for more details.

rnet/__init__.pyi CHANGED
@@ -1,6 +1,8 @@
1
+ import datetime
1
2
  import ipaddress
2
- import typing
3
3
  from typing import (
4
+ AsyncGenerator,
5
+ Generator,
4
6
  Optional,
5
7
  Tuple,
6
8
  Union,
@@ -11,121 +13,876 @@ from typing import (
11
13
  )
12
14
  from pathlib import Path
13
15
  from enum import Enum, auto
16
+ from typing import Unpack, NotRequired
14
17
 
15
- from .cookie import *
16
- from .exceptions import *
17
- from .header import *
18
- from .emulation import *
19
- from .tls import *
18
+ from .cookie import Cookie, Jar
19
+ from .header import HeaderMap, OrigHeaderMap
20
+ from .emulation import Emulation, EmulationOption
21
+ from .tls import TlsVersion, Identity, KeyLogPolicy, CertStore
20
22
 
21
- try:
22
- from typing import Unpack, NotRequired
23
- except ImportError:
24
- from typing_extensions import Unpack, NotRequired
23
+ class Method(Enum):
24
+ r"""
25
+ An HTTP method.
26
+ """
27
+
28
+ GET = auto()
29
+ HEAD = auto()
30
+ POST = auto()
31
+ PUT = auto()
32
+ DELETE = auto()
33
+ OPTIONS = auto()
34
+ TRACE = auto()
35
+ PATCH = auto()
36
+
37
+ class Version(Enum):
38
+ r"""
39
+ An HTTP version.
40
+ """
41
+
42
+ HTTP_09 = auto()
43
+ HTTP_10 = auto()
44
+ HTTP_11 = auto()
45
+ HTTP_2 = auto()
46
+ HTTP_3 = auto()
47
+
48
+ class StatusCode:
49
+ r"""
50
+ HTTP status code.
51
+ """
52
+
53
+ def __str__(self) -> str: ...
54
+ def as_int(self) -> int:
55
+ r"""
56
+ Return the status code as an integer.
57
+ """
58
+ ...
59
+
60
+ def is_informational(self) -> bool:
61
+ r"""
62
+ Check if status is within 100-199.
63
+ """
64
+ ...
65
+
66
+ def is_success(self) -> bool:
67
+ r"""
68
+ Check if status is within 200-299.
69
+ """
70
+ ...
71
+
72
+ def is_redirection(self) -> bool:
73
+ r"""
74
+ Check if status is within 300-399.
75
+ """
76
+ ...
77
+
78
+ def is_client_error(self) -> bool:
79
+ r"""
80
+ Check if status is within 400-499.
81
+ """
82
+ ...
83
+
84
+ def is_server_error(self) -> bool:
85
+ r"""
86
+ Check if status is within 500-599.
87
+ """
88
+ ...
89
+
90
+ class SocketAddr:
91
+ r"""
92
+ A IP socket address.
93
+ """
94
+
95
+ def __str__(self) -> str: ...
96
+ def ip(self) -> Union[ipaddress.IPv4Address, ipaddress.IPv6Address]:
97
+ r"""
98
+ Returns the IP address of the socket address.
99
+ """
100
+
101
+ def port(self) -> int:
102
+ r"""
103
+ Returns the port number of the socket address.
104
+ """
105
+
106
+ class Multipart:
107
+ r"""
108
+ A multipart form for a request.
109
+ """
110
+
111
+ def __init__(self, *parts) -> None:
112
+ r"""
113
+ Creates a new multipart form.
114
+ """
115
+ ...
116
+
117
+ class Part:
118
+ r"""
119
+ A part of a multipart form.
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ name: str,
125
+ value: Union[
126
+ str,
127
+ bytes,
128
+ Path,
129
+ Generator[bytes, str, None],
130
+ AsyncGenerator[bytes, str],
131
+ ],
132
+ filename: str | None = None,
133
+ mime: str | None = None,
134
+ length: int | None = None,
135
+ headers: HeaderMap | None = None,
136
+ ) -> None:
137
+ r"""
138
+ Creates a new part.
139
+
140
+ # Arguments
141
+ - `name` - The name of the part.
142
+ - `value` - The value of the part, either text, bytes, a file path, or a async or sync stream.
143
+ - `filename` - The filename of the part.
144
+ - `mime` - The MIME type of the part.
145
+ - `length` - The length of the part when value is a stream (e.g., for file uploads).
146
+ - `headers` - The custom headers for the part.
147
+ """
148
+ ...
149
+
150
+ class ProxyParams(TypedDict):
151
+ username: NotRequired[str]
152
+ r"""Username for proxy authentication."""
153
+
154
+ password: NotRequired[str]
155
+ r"""Password for proxy authentication."""
156
+
157
+ custom_http_auth: NotRequired[str]
158
+ r"""Custom HTTP proxy authentication header value."""
159
+
160
+ custom_http_headers: NotRequired[Union[Dict[str, str], HeaderMap]]
161
+ r"""Custom HTTP proxy headers."""
162
+
163
+ exclusion: NotRequired[str]
164
+ r"""List of domains to exclude from proxying."""
165
+
166
+ class Proxy:
167
+ r"""
168
+ A proxy server for a request.
169
+ Supports HTTP, HTTPS, SOCKS4, SOCKS4a, SOCKS5, and SOCKS5h protocols.
170
+ """
171
+
172
+ @staticmethod
173
+ def http(url: str, **kwargs: Unpack[ProxyParams]) -> "Proxy":
174
+ r"""
175
+ Creates a new HTTP proxy.
176
+
177
+ This method sets up a proxy server for HTTP requests.
178
+
179
+ # Examples
180
+
181
+ ```python
182
+ import rnet
183
+
184
+ proxy = rnet.Proxy.http("http://proxy.example.com")
185
+ ```
186
+ """
187
+
188
+ @staticmethod
189
+ def https(url: str, **kwargs: Unpack[ProxyParams]) -> "Proxy":
190
+ r"""
191
+ Creates a new HTTPS proxy.
192
+
193
+ This method sets up a proxy server for HTTPS requests.
194
+
195
+ # Examples
196
+
197
+ ```python
198
+ import rnet
199
+
200
+ proxy = rnet.Proxy.https("https://proxy.example.com")
201
+ ```
202
+ """
203
+
204
+ @staticmethod
205
+ def all(url: str, **kwargs: Unpack[ProxyParams]) -> "Proxy":
206
+ r"""
207
+ Creates a new proxy for all protocols.
208
+
209
+ This method sets up a proxy server for all types of requests (HTTP, HTTPS, etc.).
210
+
211
+ # Examples
212
+
213
+ ```python
214
+ import rnet
215
+
216
+ proxy = rnet.Proxy.all("https://proxy.example.com")
217
+ ```
218
+ """
219
+
220
+ class Message:
221
+ r"""
222
+ A WebSocket message.
223
+ """
224
+
225
+ data: Optional[bytes]
226
+ r"""
227
+ Returns the data of the message as bytes.
228
+ """
229
+
230
+ text: Optional[str]
231
+ r"""
232
+ Returns the text content of the message if it is a text message.
233
+ """
234
+
235
+ binary: Optional[bytes]
236
+ r"""
237
+ Returns the binary data of the message if it is a binary message.
238
+ """
239
+
240
+ ping: Optional[bytes]
241
+ r"""
242
+ Returns the ping data of the message if it is a ping message.
243
+ """
244
+
245
+ pong: Optional[bytes]
246
+ r"""
247
+ Returns the pong data of the message if it is a pong message.
248
+ """
249
+
250
+ close: Optional[Tuple[int, Optional[str]]]
251
+ r"""
252
+ Returns the close code and reason of the message if it is a close message.
253
+ """
254
+
255
+ @staticmethod
256
+ def text_from_json(json: Dict[str, Any]) -> "Message":
257
+ r"""
258
+ Creates a new text message from the JSON representation.
259
+
260
+ # Arguments
261
+ * `json` - The JSON representation of the message.
262
+ """
263
+ ...
264
+
265
+ @staticmethod
266
+ def binary_from_json(json: Dict[str, Any]) -> "Message":
267
+ r"""
268
+ Creates a new binary message from the JSON representation.
269
+
270
+ # Arguments
271
+ * `json` - The JSON representation of the message.
272
+ """
273
+
274
+ @staticmethod
275
+ def from_text(text: str) -> "Message":
276
+ r"""
277
+ Creates a new text message.
278
+
279
+ # Arguments
280
+
281
+ * `text` - The text content of the message.
282
+ """
283
+
284
+ @staticmethod
285
+ def from_binary(data: bytes) -> "Message":
286
+ r"""
287
+ Creates a new binary message.
288
+
289
+ # Arguments
290
+
291
+ * `data` - The binary data of the message.
292
+ """
293
+
294
+ @staticmethod
295
+ def from_ping(data: bytes) -> "Message":
296
+ r"""
297
+ Creates a new ping message.
298
+
299
+ # Arguments
300
+
301
+ * `data` - The ping data of the message.
302
+ """
303
+
304
+ @staticmethod
305
+ def from_pong(data: bytes) -> "Message":
306
+ r"""
307
+ Creates a new pong message.
308
+
309
+ # Arguments
310
+
311
+ * `data` - The pong data of the message.
312
+ """
313
+
314
+ @staticmethod
315
+ def from_close(code: int, reason: str | None = None) -> "Message":
316
+ r"""
317
+ Creates a new close message.
318
+
319
+ # Arguments
320
+
321
+ * `code` - The close code.
322
+ * `reason` - An optional reason for closing.
323
+ """
324
+
325
+ def json(self) -> Dict[str, Any]:
326
+ r"""
327
+ Returns the JSON representation of the message.
328
+ """
329
+
330
+ def __str__(self) -> str: ...
331
+
332
+ class History:
333
+ """
334
+ An entry in the redirect history.
335
+ """
336
+
337
+ status: int
338
+ """Get the status code of the redirect response."""
339
+
340
+ url: str
341
+ """Get the URL of the redirect response."""
342
+
343
+ previous: str
344
+ """Get the previous URL before the redirect response."""
345
+
346
+ headers: HeaderMap
347
+ """Get the headers of the redirect response."""
348
+
349
+ def __str__(self) -> str: ...
350
+
351
+ class Streamer:
352
+ r"""
353
+ A byte stream response.
354
+ An asynchronous iterator yielding data chunks from the response stream.
355
+ Used to stream response content.
356
+ Implemented in the `stream` method of the `Response` class.
357
+ Can be used in an asynchronous for loop in Python.
358
+
359
+ # Examples
360
+
361
+ ```python
362
+ import asyncio
363
+ import rnet
364
+ from rnet import Method, Emulation
365
+
366
+ async def main():
367
+ resp = await rnet.get("https://httpbin.org/stream/20")
368
+ async with resp.stream() as streamer:
369
+ async for chunk in streamer:
370
+ print("Chunk: ", chunk)
371
+ await asyncio.sleep(0.1)
372
+
373
+ if __name__ == "__main__":
374
+ asyncio.run(main())
375
+ ```
376
+ """
377
+
378
+ async def __aiter__(self) -> "Streamer": ...
379
+ async def __anext__(self) -> Optional[bytes]: ...
380
+ async def __aenter__(self) -> Any: ...
381
+ async def __aexit__(
382
+ self, _exc_type: Any, _exc_value: Any, _traceback: Any
383
+ ) -> Any: ...
384
+ def __iter__(self) -> "Streamer": ...
385
+ def __next__(self) -> bytes: ...
386
+ def __enter__(self) -> "Streamer": ...
387
+ def __exit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> None: ...
388
+
389
+ class Response:
390
+ r"""
391
+ A response from a request.
392
+
393
+ # Examples
394
+
395
+ ```python
396
+ import asyncio
397
+ import rnet
398
+
399
+ async def main():
400
+ response = await rnet.get("https://www.rust-lang.org")
401
+ print("Status Code: ", response.status)
402
+ print("Version: ", response.version)
403
+ print("Response URL: ", response.url)
404
+ print("Headers: ", response.headers)
405
+ print("Content-Length: ", response.content_length)
406
+ print("Encoding: ", response.encoding)
407
+ print("Remote Address: ", response.remote_addr)
408
+
409
+ text_content = await response.text()
410
+ print("Text: ", text_content)
411
+
412
+ if __name__ == "__main__":
413
+ asyncio.run(main())
414
+ ```
415
+ """
416
+
417
+ url: str
418
+ r"""
419
+ Get the URL of the response.
420
+ """
421
+
422
+ status: StatusCode
423
+ r"""
424
+ Get the status code of the response.
425
+ """
426
+
427
+ version: Version
428
+ r"""
429
+ Get the HTTP version of the response.
430
+ """
431
+
432
+ headers: HeaderMap
433
+ r"""
434
+ Get the headers of the response.
435
+ """
436
+
437
+ cookies: List[Cookie]
438
+ r"""
439
+ Get the cookies of the response.
440
+ """
441
+
442
+ content_length: Optional[int]
443
+ r"""
444
+ Get the content length of the response.
445
+ """
446
+
447
+ remote_addr: Optional[SocketAddr]
448
+ r"""
449
+ Get the remote address of the response.
450
+ """
451
+
452
+ local_addr: Optional[SocketAddr]
453
+ r"""
454
+ Get the local address of the response.
455
+ """
456
+
457
+ history: List[History]
458
+ r"""
459
+ Get the redirect history of the Response.
460
+ """
461
+
462
+ peer_certificate: Optional[bytes]
463
+ r"""
464
+ Get the DER encoded leaf certificate of the response.
465
+ """
466
+
467
+ async def text(self) -> str:
468
+ r"""
469
+ Get the text content of the response.
470
+ """
471
+
472
+ async def text_with_charset(self, encoding: str) -> str:
473
+ r"""
474
+ Get the full response text given a specific encoding.
475
+ """
476
+
477
+ async def json(self) -> Any:
478
+ r"""
479
+ Get the JSON content of the response.
480
+ """
481
+
482
+ async def bytes(self) -> bytes:
483
+ r"""
484
+ Get the bytes content of the response.
485
+ """
486
+
487
+ def stream(self) -> Streamer:
488
+ r"""
489
+ Get the response into a `Stream` of `Bytes` from the body.
490
+ """
25
491
 
26
- class ClientParams(TypedDict, closed=True):
492
+ async def close(self) -> None:
493
+ r"""
494
+ Close the response connection.
495
+ """
496
+
497
+ async def __aenter__(self) -> Any: ...
498
+ async def __aexit__(
499
+ self, _exc_type: Any, _exc_value: Any, _traceback: Any
500
+ ) -> Any: ...
501
+
502
+ class WebSocket:
503
+ r"""
504
+ A WebSocket response.
505
+ """
506
+
507
+ status: StatusCode
508
+ r"""
509
+ Get the status code of the response.
510
+ """
511
+
512
+ version: Version
513
+ r"""
514
+ Get the HTTP version of the response.
515
+ """
516
+
517
+ headers: HeaderMap
518
+ r"""
519
+ Get the headers of the response.
520
+ """
521
+
522
+ cookies: List[Cookie]
523
+ r"""
524
+ Get the cookies of the response.
525
+ """
526
+
527
+ remote_addr: Optional[SocketAddr]
528
+ r"""
529
+ Get the remote address of the response.
530
+ """
531
+
532
+ protocol: Optional[str]
533
+ r"""
534
+ Get the WebSocket protocol.
535
+ """
536
+
537
+ async def recv(
538
+ self, timeout: datetime.timedelta | None = None
539
+ ) -> Optional[Message]:
540
+ r"""
541
+ Receive a message from the WebSocket.
542
+ """
543
+
544
+ async def send(self, message: Message) -> None:
545
+ r"""
546
+ Send a message to the WebSocket.
547
+
548
+ # Arguments
549
+
550
+ * `message` - The message to send.
551
+ """
552
+
553
+ async def send_all(self, messages: List[Message]) -> None:
554
+ r"""
555
+ Send multiple messages to the WebSocket.
556
+
557
+ # Arguments
558
+
559
+ * `messages` - The list of messages to send.
560
+ """
561
+
562
+ async def close(
563
+ self,
564
+ code: int | None = None,
565
+ reason: str | None = None,
566
+ ) -> None:
567
+ r"""
568
+ Close the WebSocket connection.
569
+
570
+ # Arguments
571
+
572
+ * `code` - An optional close code.
573
+ * `reason` - An optional reason for closing.
574
+ """
575
+
576
+ def __aenter__(self) -> Any: ...
577
+ def __aexit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> Any: ...
578
+
579
+ class ClientParams(TypedDict):
27
580
  emulation: NotRequired[Union[Emulation, EmulationOption]]
581
+ """Browser fingerprint/Emulation config."""
582
+
28
583
  user_agent: NotRequired[str]
584
+ """Default User-Agent string."""
585
+
29
586
  headers: NotRequired[Union[Dict[str, str], HeaderMap]]
587
+ """Default request headers."""
588
+
30
589
  orig_headers: NotRequired[Union[List[str], OrigHeaderMap]]
590
+ """Original request headers (case-sensitive and order)."""
591
+
31
592
  referer: NotRequired[bool]
593
+ """Automatically set Referer."""
594
+
595
+ history: NotRequired[bool]
596
+ """Store redirect history."""
597
+
32
598
  allow_redirects: NotRequired[bool]
599
+ """Allow automatic redirects."""
600
+
33
601
  max_redirects: NotRequired[int]
602
+ """Maximum number of redirects."""
603
+
34
604
  cookie_store: NotRequired[bool]
605
+ """Enable cookie store."""
606
+
35
607
  cookie_provider: NotRequired[Jar]
608
+ """Custom cookie provider."""
609
+
610
+ lookup_ip_strategy: NotRequired[str]
611
+ """IP lookup strategy."""
612
+
36
613
  timeout: NotRequired[int]
614
+ """Total timeout (seconds)."""
615
+
37
616
  connect_timeout: NotRequired[int]
617
+ """Connection timeout (seconds)."""
618
+
38
619
  read_timeout: NotRequired[int]
620
+ """Read timeout (seconds)."""
621
+
39
622
  tcp_keepalive: NotRequired[int]
623
+ """TCP keepalive time (seconds)."""
624
+
40
625
  tcp_keepalive_interval: NotRequired[int]
626
+ """TCP keepalive interval (seconds)."""
627
+
41
628
  tcp_keepalive_retries: NotRequired[int]
629
+ """TCP keepalive retry count."""
630
+
42
631
  tcp_user_timeout: NotRequired[int]
632
+ """TCP user timeout (seconds)."""
633
+
43
634
  tcp_nodelay: NotRequired[bool]
635
+ """Enable TCP_NODELAY."""
636
+
44
637
  tcp_reuse_address: NotRequired[bool]
638
+ """Enable SO_REUSEADDR."""
639
+
45
640
  pool_idle_timeout: NotRequired[int]
641
+ """Connection pool idle timeout (seconds)."""
642
+
46
643
  pool_max_idle_per_host: NotRequired[int]
644
+ """Max idle connections per host."""
645
+
47
646
  pool_max_size: NotRequired[int]
647
+ """Max total connections in pool."""
648
+
48
649
  http1_only: NotRequired[bool]
650
+ """Enable HTTP/1.1 only."""
651
+
49
652
  http2_only: NotRequired[bool]
653
+ """Enable HTTP/2 only."""
654
+
50
655
  https_only: NotRequired[bool]
51
- http2_max_retry_count: NotRequired[int]
656
+ """Enable HTTPS only."""
657
+
52
658
  verify: NotRequired[Union[bool, Path, CertStore]]
659
+ """Verify SSL or specify CA path."""
660
+
53
661
  identity: NotRequired[Identity]
662
+ """Represents a private key and X509 cert as a client certificate."""
663
+
54
664
  keylog: NotRequired[KeyLogPolicy]
665
+ """Key logging policy (environment or file)."""
666
+
55
667
  tls_info: NotRequired[bool]
668
+ """Return TLS info."""
669
+
56
670
  min_tls_version: NotRequired[TlsVersion]
671
+ """Minimum TLS version."""
672
+
57
673
  max_tls_version: NotRequired[TlsVersion]
674
+ """Maximum TLS version."""
675
+
58
676
  no_proxy: NotRequired[bool]
677
+ """Disable proxy."""
678
+
59
679
  proxies: NotRequired[List[Proxy]]
680
+ """Proxy server list."""
681
+
60
682
  local_address: NotRequired[Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address]]
683
+ """Local bind address."""
684
+
61
685
  interface: NotRequired[str]
686
+ """Local network interface."""
687
+
62
688
  gzip: NotRequired[bool]
689
+ """Enable gzip decompression."""
690
+
63
691
  brotli: NotRequired[bool]
692
+ """Enable brotli decompression."""
693
+
64
694
  deflate: NotRequired[bool]
65
- zstd: NotRequired[bool]
695
+ """Enable deflate decompression."""
66
696
 
67
- class ProxyParams(TypedDict, closed=True):
68
- username: NotRequired[str]
69
- password: NotRequired[str]
70
- custom_http_auth: NotRequired[str]
71
- custom_http_headers: NotRequired[Union[Dict[str, str], HeaderMap]]
72
- exclusion: NotRequired[str]
697
+ zstd: NotRequired[bool]
698
+ """Enable zstd decompression."""
73
699
 
74
- class Request(TypedDict, closed=True):
700
+ class Request(TypedDict):
75
701
  emulation: NotRequired[Union[Emulation, EmulationOption]]
702
+ """The Emulation settings for the request."""
703
+
76
704
  proxy: NotRequired[Proxy]
705
+ """The proxy to use for the request."""
706
+
77
707
  local_address: NotRequired[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]]
708
+ """Bind to a local IP Address."""
709
+
78
710
  interface: NotRequired[str]
711
+ """Bind to an interface by SO_BINDTODEVICE."""
712
+
79
713
  timeout: NotRequired[int]
714
+ """The timeout to use for the request."""
715
+
80
716
  read_timeout: NotRequired[int]
717
+ """The read timeout to use for the request."""
718
+
81
719
  version: NotRequired[Version]
720
+ """The HTTP version to use for the request."""
721
+
82
722
  headers: NotRequired[Union[Dict[str, str], HeaderMap]]
723
+ """The headers to use for the request."""
724
+
83
725
  orig_headers: NotRequired[Union[List[str], OrigHeaderMap]]
726
+ """The original headers to use for the request."""
727
+
84
728
  default_headers: NotRequired[bool]
729
+ """The option enables default headers."""
730
+
85
731
  cookies: NotRequired[Dict[str, str]]
732
+ """The cookies to use for the request."""
733
+
86
734
  allow_redirects: NotRequired[bool]
735
+ """Whether to allow redirects."""
736
+
87
737
  max_redirects: NotRequired[int]
738
+ """The maximum number of redirects to follow."""
739
+
88
740
  gzip: NotRequired[bool]
741
+ """Sets gzip as an accepted encoding."""
742
+
89
743
  brotli: NotRequired[bool]
744
+ """Sets brotli as an accepted encoding."""
745
+
90
746
  deflate: NotRequired[bool]
747
+ """Sets deflate as an accepted encoding."""
748
+
91
749
  zstd: NotRequired[bool]
750
+ """Sets zstd as an accepted encoding."""
751
+
92
752
  auth: NotRequired[str]
753
+ """The authentication to use for the request."""
754
+
93
755
  bearer_auth: NotRequired[str]
756
+ """The bearer authentication to use for the request."""
757
+
94
758
  basic_auth: NotRequired[Tuple[str, Optional[str]]]
759
+ """The basic authentication to use for the request."""
760
+
95
761
  query: NotRequired[List[Tuple[str, str]]]
762
+ """The query parameters to use for the request."""
763
+
96
764
  form: NotRequired[List[Tuple[str, str]]]
765
+ """The form parameters to use for the request."""
766
+
97
767
  json: NotRequired[Dict[str, Any]]
768
+ """The JSON body to use for the request."""
769
+
98
770
  body: NotRequired[
99
771
  Union[
100
772
  str,
101
773
  bytes,
102
- typing.AsyncGenerator[bytes, str],
103
- typing.Generator[bytes, str],
774
+ Generator[bytes, str, None],
775
+ AsyncGenerator[bytes, str],
104
776
  ]
105
777
  ]
778
+ """The body to use for the request."""
779
+
106
780
  multipart: NotRequired[Multipart]
781
+ """The multipart form to use for the request."""
107
782
 
108
- class WebSocketRequest(TypedDict, closed=True):
783
+ class WebSocketRequest(TypedDict):
109
784
  emulation: NotRequired[Union[Emulation, EmulationOption]]
785
+ """The Emulation settings for the request."""
786
+
110
787
  proxy: NotRequired[Proxy]
788
+ """The proxy to use for the request."""
789
+
111
790
  local_address: NotRequired[Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address]]
791
+ """Bind to a local IP Address."""
792
+
112
793
  interface: NotRequired[str]
794
+ """Bind to an interface by SO_BINDTODEVICE."""
795
+
113
796
  headers: NotRequired[Union[Dict[str, str], HeaderMap]]
797
+ """The headers to use for the request."""
798
+
114
799
  orig_headers: NotRequired[Union[List[str], OrigHeaderMap]]
800
+ """The original headers to use for the request."""
801
+
115
802
  default_headers: NotRequired[bool]
803
+ """The option enables default headers."""
804
+
116
805
  cookies: NotRequired[Dict[str, str]]
806
+ """The cookies to use for the request."""
807
+
117
808
  protocols: NotRequired[List[str]]
809
+ """The protocols to use for the request."""
810
+
118
811
  force_http2: NotRequired[bool]
812
+ """Whether to use HTTP/2 for the websocket."""
813
+
119
814
  auth: NotRequired[str]
815
+ """The authentication to use for the request."""
816
+
120
817
  bearer_auth: NotRequired[str]
818
+ """The bearer authentication to use for the request."""
819
+
121
820
  basic_auth: NotRequired[Tuple[str, Optional[str]]]
821
+ """The basic authentication to use for the request."""
822
+
122
823
  query: NotRequired[List[Tuple[str, str]]]
824
+ """The query parameters to use for the request."""
825
+
123
826
  read_buffer_size: NotRequired[int]
827
+ """
828
+ Read buffer capacity. This buffer is eagerly allocated and used for receiving messages.
829
+
830
+ For high read load scenarios a larger buffer, e.g. 128 KiB, improves performance.
831
+
832
+ For scenarios where you expect a lot of connections and don't need high read load
833
+ performance a smaller buffer, e.g. 4 KiB, would be appropriate to lower total
834
+ memory usage.
835
+
836
+ The default value is 128 KiB.
837
+ """
838
+
124
839
  write_buffer_size: NotRequired[int]
840
+ """
841
+ The target minimum size of the write buffer to reach before writing the data
842
+ to the underlying stream. The default value is 128 KiB.
843
+
844
+ If set to 0 each message will be eagerly written to the underlying stream.
845
+ It is often more optimal to allow them to buffer a little, hence the default value.
846
+
847
+ Note: flush() will always fully write the buffer regardless.
848
+ """
849
+
125
850
  max_write_buffer_size: NotRequired[int]
851
+ """
852
+ The max size of the write buffer in bytes. Setting this can provide backpressure
853
+ in the case the write buffer is filling up due to write errors.
854
+ The default value is unlimited.
855
+
856
+ Note: The write buffer only builds up past write_buffer_size when writes to the
857
+ underlying stream are failing. So the write buffer can not fill up if you are not
858
+ observing write errors even if not flushing.
859
+
860
+ Note: Should always be at least write_buffer_size + 1 message and probably a little
861
+ more depending on error handling strategy.
862
+ """
863
+
126
864
  max_message_size: NotRequired[int]
865
+ """
866
+ The maximum size of an incoming message. None means no size limit.
867
+ The default value is 64 MiB which should be reasonably big for all normal use-cases
868
+ but small enough to prevent memory eating by a malicious user.
869
+ """
870
+
127
871
  max_frame_size: NotRequired[int]
872
+ """
873
+ The maximum size of a single incoming message frame. None means no size limit.
874
+ The limit is for frame payload NOT including the frame header.
875
+ The default value is 16 MiB which should be reasonably big for all normal use-cases
876
+ but small enough to prevent memory eating by a malicious user.
877
+ """
878
+
128
879
  accept_unmasked_frames: NotRequired[bool]
880
+ """
881
+ When set to True, the server will accept and handle unmasked frames from the client.
882
+ According to RFC 6455, the server must close the connection to the client in such cases,
883
+ however it seems like there are some popular libraries that are sending unmasked frames,
884
+ ignoring the RFC. By default this option is set to False, i.e. according to RFC6455.
885
+ """
129
886
 
130
887
  class Client:
131
888
  r"""
@@ -133,67 +890,30 @@ class Client:
133
890
  """
134
891
 
135
892
  def __init__(
136
- cls,
893
+ self,
137
894
  **kwargs: Unpack[ClientParams],
138
- ) -> Client:
895
+ ) -> None:
139
896
  r"""
140
897
  Creates a new Client instance.
141
898
 
142
- Args:
143
- emulation: Browser fingerprint/Emulation config.
144
- user_agent: Default User-Agent string.
145
- headers: Default request headers.
146
- orig_headers: Original request headers (case-sensitive and order).
147
- referer: Automatically set Referer.
148
- allow_redirects: Allow automatic redirects.
149
- max_redirects: Maximum number of redirects.
150
- cookie_store: Enable cookie store.
151
- lookup_ip_strategy: IP lookup strategy.
152
- timeout: Total timeout (seconds).
153
- connect_timeout: Connection timeout (seconds).
154
- read_timeout: Read timeout (seconds).
155
- tcp_keepalive: TCP keepalive time (seconds).
156
- tcp_keepalive_interval: TCP keepalive interval (seconds).
157
- tcp_keepalive_retries: TCP keepalive retry count.
158
- tcp_user_timeout: TCP user timeout (seconds).
159
- tcp_nodelay: Enable TCP_NODELAY.
160
- tcp_reuse_address: Enable SO_REUSEADDR.
161
- pool_idle_timeout: Connection pool idle timeout (seconds).
162
- pool_max_idle_per_host: Max idle connections per host.
163
- pool_max_size: Max total connections in pool.
164
- http1_only: Enable HTTP/1.1 only.
165
- http2_only: Enable HTTP/2 only.
166
- https_only: Enable HTTPS only.
167
- http2_max_retry_count: Max HTTP/2 retry count.
168
- verify: Verify SSL or specify CA path.
169
- identity: Represents a private key and X509 cert as a client certificate.
170
- keylog: Key logging policy (environment or file).
171
- tls_info: Return TLS info.
172
- min_tls_version: Minimum TLS version.
173
- max_tls_version: Maximum TLS version.
174
- no_proxy: Disable proxy.
175
- proxies: Proxy server list.
176
- local_address: Local bind address.
177
- interface: Local network interface.
178
- gzip: Enable gzip decompression.
179
- brotli: Enable brotli decompression.
180
- deflate: Enable deflate decompression.
181
- zstd: Enable zstd decompression.
182
-
183
899
  Examples:
184
900
 
185
- ```python
186
- import asyncio
187
- import rnet
901
+ ```python
902
+ import asyncio
903
+ import rnet
188
904
 
905
+ async def main():
189
906
  client = rnet.Client(
190
- user_agent="my-app/0.0.1",
907
+ user_agent="Mozilla/5.0",
191
908
  timeout=10,
192
909
  )
193
910
  response = await client.get('https://httpbin.org/get')
194
- print(response.text)
195
- ```
911
+ print(await response.text())
912
+
913
+ asyncio.run(main())
914
+ ```
196
915
  """
916
+ ...
197
917
 
198
918
  async def request(
199
919
  self,
@@ -419,263 +1139,24 @@ class Client:
419
1139
  url: str,
420
1140
  **kwargs: Unpack[Request],
421
1141
  ) -> Response:
422
- r"""
423
- Sends a request with the given URL
424
-
425
- # Examples
426
-
427
- ```python
428
- import rnet
429
- import asyncio
430
- from rnet import Method
431
-
432
- async def main():
433
- client = rnet.Client()
434
- response = await client.get("https://httpbin.org/anything")
435
- print(await response.text())
436
-
437
- asyncio.run(main())
438
- ```
439
- """
440
-
441
- class Multipart:
442
- r"""
443
- A multipart form for a request.
444
- """
445
-
446
- def __init__(cls, *parts) -> Multipart:
447
- r"""
448
- Creates a new multipart form.
449
- """
450
-
451
- class Part:
452
- r"""
453
- A part of a multipart form.
454
- """
455
-
456
- def __init__(
457
- cls,
458
- name: str,
459
- value: Union[
460
- str,
461
- bytes,
462
- Path,
463
- typing.AsyncGenerator[bytes, str],
464
- typing.Generator[bytes, str],
465
- ],
466
- filename: Optional[str] = None,
467
- mime: Optional[str] = None,
468
- ) -> Part:
469
- r"""
470
- Creates a new part.
471
-
472
- # Arguments
473
- - `name` - The name of the part.
474
- - `value` - The value of the part, either text, bytes, a file path, or a async or sync stream.
475
- - `filename` - The filename of the part.
476
- - `mime` - The MIME type of the part.
477
- """
478
-
479
- class Response:
480
- r"""
481
- A response from a request.
482
-
483
- # Examples
484
-
485
- ```python
486
- import asyncio
487
- import rnet
488
-
489
- async def main():
490
- response = await rnet.get("https://www.rust-lang.org")
491
- print("Status Code: ", response.status)
492
- print("Version: ", response.version)
493
- print("Response URL: ", response.url)
494
- print("Headers: ", response.headers)
495
- print("Content-Length: ", response.content_length)
496
- print("Encoding: ", response.encoding)
497
- print("Remote Address: ", response.remote_addr)
498
-
499
- text_content = await response.text()
500
- print("Text: ", text_content)
501
-
502
- if __name__ == "__main__":
503
- asyncio.run(main())
504
- ```
505
- """
506
-
507
- url: str
508
- r"""
509
- Returns the URL of the response.
510
- """
511
- status: StatusCode
512
- r"""
513
- Returns the status code of the response.
514
- """
515
- version: Version
516
- r"""
517
- Returns the HTTP version of the response.
518
- """
519
- headers: HeaderMap
520
- r"""
521
- Returns the headers of the response.
522
- """
523
- cookies: List[Cookie]
524
- r"""
525
- Returns the cookies of the response.
526
- """
527
- content_length: int
528
- r"""
529
- Returns the content length of the response.
530
- """
531
- remote_addr: Optional[SocketAddr]
532
- r"""
533
- Returns the remote address of the response.
534
- """
535
- local_addr: Optional[SocketAddr]
536
- r"""
537
- Returns the local address of the response.
538
- """
539
- encoding: str
540
- r"""
541
- Encoding to decode with when accessing text.
542
- """
543
- def __aenter__(self) -> Any: ...
544
- def __aexit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> Any: ...
545
- def peer_certificate(self) -> Optional[bytes]:
546
- r"""
547
- Returns the TLS peer certificate of the response.
548
- """
549
-
550
- async def text(self) -> str:
551
- r"""
552
- Returns the text content of the response.
553
- """
554
-
555
- async def text_with_charset(self, encoding: str) -> str:
556
- r"""
557
- Returns the text content of the response with a specific charset.
558
-
559
- # Arguments
560
-
561
- * `encoding` - The default encoding to use if the charset is not specified.
562
- """
563
-
564
- async def json(self) -> Any:
565
- r"""
566
- Returns the JSON content of the response.
567
- """
568
-
569
- async def bytes(self) -> bytes:
570
- r"""
571
- Returns the bytes content of the response.
572
- """
573
-
574
- def stream(self) -> Streamer:
575
- r"""
576
- Convert the response into a `Stream` of `Bytes` from the body.
577
- """
578
-
579
- async def close(self) -> None:
580
- r"""
581
- Closes the response connection.
582
- """
583
-
584
- class SocketAddr:
585
- r"""
586
- A IP socket address.
587
- """
588
-
589
- def __str__(self) -> str: ...
590
- def ip(self) -> Union[ipaddress.IPv4Address, ipaddress.IPv6Address]:
591
- r"""
592
- Returns the IP address of the socket address.
593
- """
594
-
595
- def port(self) -> int:
596
- r"""
597
- Returns the port number of the socket address.
598
- """
599
-
600
- class StatusCode:
601
- r"""
602
- HTTP status code.
603
- """
604
-
605
- def __str__(self) -> str: ...
606
- def as_int(self) -> int:
607
- r"""
608
- Return the status code as an integer.
609
- """
610
-
611
- def is_informational(self) -> bool:
612
- r"""
613
- Check if status is within 100-199.
614
- """
615
-
616
- def is_success(self) -> bool:
617
- r"""
618
- Check if status is within 200-299.
619
- """
620
-
621
- def is_redirection(self) -> bool:
622
- r"""
623
- Check if status is within 300-399.
624
- """
625
-
626
- def is_client_error(self) -> bool:
627
- r"""
628
- Check if status is within 400-499.
629
- """
630
-
631
- def is_server_error(self) -> bool:
632
- r"""
633
- Check if status is within 500-599.
634
- """
635
-
636
- class Streamer:
637
- r"""
638
- A byte stream response.
639
- An asynchronous iterator yielding data chunks from the response stream.
640
- Used to stream response content.
641
- Implemented in the `stream` method of the `Response` class.
642
- Can be used in an asynchronous for loop in Python.
643
-
644
- # Examples
645
-
646
- ```python
647
- import asyncio
648
- import rnet
649
- from rnet import Method, Emulation
1142
+ r"""
1143
+ Sends a request with the given URL
650
1144
 
651
- async def main():
652
- resp = await rnet.get("https://httpbin.org/stream/20")
653
- print("Status Code: ", resp.status)
654
- print("Version: ", resp.version)
655
- print("Response URL: ", resp.url)
656
- print("Headers: ", resp.headers)
657
- print("Content-Length: ", resp.content_length)
658
- print("Encoding: ", resp.encoding)
659
- print("Remote Address: ", resp.remote_addr)
1145
+ # Examples
660
1146
 
661
- async with resp.stream() as streamer:
662
- async for chunk in streamer:
663
- print("Chunk: ", chunk)
664
- await asyncio.sleep(0.1)
1147
+ ```python
1148
+ import rnet
1149
+ import asyncio
1150
+ from rnet import Method
665
1151
 
666
- if __name__ == "__main__":
667
- asyncio.run(main())
668
- ```
669
- """
1152
+ async def main():
1153
+ client = rnet.Client()
1154
+ response = await client.get("https://httpbin.org/anything")
1155
+ print(await response.text())
670
1156
 
671
- def __aiter__(self) -> Streamer: ...
672
- def __anext__(self) -> Any: ...
673
- def __aenter__(self) -> Any: ...
674
- def __aexit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> Any: ...
675
- def __iter__(self) -> Streamer: ...
676
- def __next__(self) -> Any: ...
677
- def __enter__(self) -> Streamer: ...
678
- def __exit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> None: ...
1157
+ asyncio.run(main())
1158
+ ```
1159
+ """
679
1160
 
680
1161
  async def delete(
681
1162
  url: str,
@@ -904,274 +1385,3 @@ async def websocket(
904
1385
  asyncio.run(run())
905
1386
  ```
906
1387
  """
907
-
908
- class Proxy:
909
- r"""
910
- A proxy server for a request.
911
- Supports HTTP, HTTPS, SOCKS4, SOCKS4a, SOCKS5, and SOCKS5h protocols.
912
- """
913
-
914
- @staticmethod
915
- def http(url: str, **kwargs: Unpack[ProxyParams]) -> Proxy:
916
- r"""
917
- Creates a new HTTP proxy.
918
-
919
- This method sets up a proxy server for HTTP requests.
920
-
921
- # Arguments
922
-
923
- * `url` - The URL of the proxy server.
924
- * `username` - Optional username for proxy authentication.
925
- * `password` - Optional password for proxy authentication.
926
- * `custom_http_auth` - Optional custom HTTP proxy authentication header value.
927
- * `custom_http_headers` - Optional custom HTTP proxy headers.
928
- * `exclusion` - Optional List of domains to exclude from proxying.
929
-
930
- # Examples
931
-
932
- ```python
933
- import rnet
934
-
935
- proxy = rnet.Proxy.http("http://proxy.example.com")
936
- ```
937
- """
938
-
939
- @staticmethod
940
- def https(url: str, **kwargs: Unpack[ProxyParams]) -> Proxy:
941
- r"""
942
- Creates a new HTTPS proxy.
943
-
944
- This method sets up a proxy server for HTTPS requests.
945
-
946
- # Arguments
947
-
948
- * `url` - The URL of the proxy server.
949
- * `username` - Optional username for proxy authentication.
950
- * `password` - Optional password for proxy authentication.
951
- * `custom_http_auth` - Optional custom HTTP proxy authentication header value.
952
- * `custom_http_headers` - Optional custom HTTP proxy headers.
953
- * `exclusion` - Optional List of domains to exclude from proxying.
954
-
955
- # Examples
956
-
957
- ```python
958
- import rnet
959
-
960
- proxy = rnet.Proxy.https("https://proxy.example.com")
961
- ```
962
- """
963
-
964
- @staticmethod
965
- def all(url: str, **kwargs: Unpack[ProxyParams]) -> Proxy:
966
- r"""
967
- Creates a new proxy for all protocols.
968
-
969
- This method sets up a proxy server for all types of requests (HTTP, HTTPS, etc.).
970
-
971
- # Arguments
972
-
973
- * `url` - The URL of the proxy server.
974
- * `username` - Optional username for proxy authentication.
975
- * `password` - Optional password for proxy authentication.
976
- * `custom_http_auth` - Optional custom HTTP proxy authentication header value.
977
- * `custom_http_headers` - Optional custom HTTP proxy headers.
978
- * `exclusion` - Optional List of domains to exclude from proxying.
979
-
980
- # Examples
981
-
982
- ```python
983
- import rnet
984
-
985
- proxy = rnet.Proxy.all("https://proxy.example.com")
986
- ```
987
- """
988
-
989
- class Message:
990
- r"""
991
- A WebSocket message.
992
- """
993
-
994
- data: Optional[bytes]
995
- r"""
996
- Returns the data of the message as bytes.
997
- """
998
- text: Optional[str]
999
- r"""
1000
- Returns the text content of the message if it is a text message.
1001
- """
1002
- binary: Optional[bytes]
1003
- r"""
1004
- Returns the binary data of the message if it is a binary message.
1005
- """
1006
- ping: Optional[bytes]
1007
- r"""
1008
- Returns the ping data of the message if it is a ping message.
1009
- """
1010
- pong: Optional[bytes]
1011
- r"""
1012
- Returns the pong data of the message if it is a pong message.
1013
- """
1014
- close: Optional[Tuple[int, Optional[str]]]
1015
- r"""
1016
- Returns the close code and reason of the message if it is a close message.
1017
- """
1018
- def __str__(self) -> str: ...
1019
- @staticmethod
1020
- def text_from_json(json: Dict[str, Any]) -> Message:
1021
- r"""
1022
- Creates a new text message from the JSON representation.
1023
-
1024
- # Arguments
1025
- * `json` - The JSON representation of the message.
1026
- """
1027
-
1028
- @staticmethod
1029
- def binary_from_json(json: Dict[str, Any]) -> Message:
1030
- r"""
1031
- Creates a new binary message from the JSON representation.
1032
-
1033
- # Arguments
1034
- * `json` - The JSON representation of the message.
1035
- """
1036
-
1037
- @staticmethod
1038
- def from_text(text: str) -> Message:
1039
- r"""
1040
- Creates a new text message.
1041
-
1042
- # Arguments
1043
-
1044
- * `text` - The text content of the message.
1045
- """
1046
-
1047
- @staticmethod
1048
- def from_binary(data: bytes) -> Message:
1049
- r"""
1050
- Creates a new binary message.
1051
-
1052
- # Arguments
1053
-
1054
- * `data` - The binary data of the message.
1055
- """
1056
-
1057
- @staticmethod
1058
- def from_ping(data: bytes) -> Message:
1059
- r"""
1060
- Creates a new ping message.
1061
-
1062
- # Arguments
1063
-
1064
- * `data` - The ping data of the message.
1065
- """
1066
-
1067
- @staticmethod
1068
- def from_pong(data: bytes) -> Message:
1069
- r"""
1070
- Creates a new pong message.
1071
-
1072
- # Arguments
1073
-
1074
- * `data` - The pong data of the message.
1075
- """
1076
-
1077
- @staticmethod
1078
- def from_close(code: int, reason: Optional[str] = None) -> Message:
1079
- r"""
1080
- Creates a new close message.
1081
-
1082
- # Arguments
1083
-
1084
- * `code` - The close code.
1085
- * `reason` - An optional reason for closing.
1086
- """
1087
-
1088
- def json(self) -> Dict[str, Any]:
1089
- r"""
1090
- Returns the JSON representation of the message.
1091
- """
1092
-
1093
- class WebSocket:
1094
- r"""
1095
- A WebSocket response.
1096
- """
1097
-
1098
- status: StatusCode
1099
- r"""
1100
- Returns the status code of the response.
1101
- """
1102
- version: Version
1103
- r"""
1104
- Returns the HTTP version of the response.
1105
- """
1106
- headers: HeaderMap
1107
- r"""
1108
- Returns the headers of the response.
1109
- """
1110
- cookies: List[Cookie]
1111
- r"""
1112
- Returns the cookies of the response.
1113
- """
1114
- remote_addr: Optional[SocketAddr]
1115
- r"""
1116
- Returns the remote address of the response.
1117
- """
1118
- protocol: Optional[str]
1119
- r"""
1120
- Returns the WebSocket protocol.
1121
- """
1122
- def __aiter__(self) -> WebSocket: ...
1123
- def __anext__(self) -> Any: ...
1124
- def __aenter__(self) -> Any: ...
1125
- def __aexit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> Any: ...
1126
- async def recv(self) -> Optional[Message]:
1127
- r"""
1128
- Receives a message from the WebSocket.
1129
- """
1130
-
1131
- async def send(self, message: Message) -> None:
1132
- r"""
1133
- Sends a message to the WebSocket.
1134
-
1135
- # Arguments
1136
-
1137
- * `message` - The message to send.
1138
- """
1139
-
1140
- async def close(
1141
- self,
1142
- code: Optional[int] = None,
1143
- reason: Optional[str] = None,
1144
- ) -> None:
1145
- r"""
1146
- Closes the WebSocket connection.
1147
-
1148
- # Arguments
1149
-
1150
- * `code` - An optional close code.
1151
- * `reason` - An optional reason for closing.
1152
- """
1153
-
1154
- class Method(Enum):
1155
- r"""
1156
- An HTTP method.
1157
- """
1158
-
1159
- GET = auto()
1160
- HEAD = auto()
1161
- POST = auto()
1162
- PUT = auto()
1163
- DELETE = auto()
1164
- OPTIONS = auto()
1165
- TRACE = auto()
1166
- PATCH = auto()
1167
-
1168
- class Version(Enum):
1169
- r"""
1170
- An HTTP version.
1171
- """
1172
-
1173
- HTTP_09 = auto()
1174
- HTTP_10 = auto()
1175
- HTTP_11 = auto()
1176
- HTTP_2 = auto()
1177
- HTTP_3 = auto()