-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.py
1035 lines (900 loc) · 32 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import datetime
import time
import typing
import uuid
from enum import Enum
from typing import (Any, Callable, Literal, Mapping, Optional, Sequence,
TypeVar, Union)
from .exceptions import ProxyError, RemoteProtocolError, TooManyRedirects
from .models import (URL, Auth, BasicAuth, Cookies, Headers, Proxy, Request,
Response, StatusCodes, TLSClient, TLSConfig, URLParams)
from .settings import (DEFAULT_FOLLOW_REDIRECTS, DEFAULT_HEADERS,
DEFAULT_MAX_REDIRECTS, DEFAULT_TIMEOUT,
DEFAULT_TLS_HTTP2, DEFAULT_TLS_IDENTIFIER)
from .types import (AuthTypes, CookieTypes, HeaderTypes, HookTypes,
ProtocolTypes, ProxyTypes, RequestData, RequestFiles,
TimeoutTypes, TLSIdentifierTypes, URLParamTypes, URLTypes)
from .utils import get_logger
__all__ = ["AsyncClient", "Client"]
T = TypeVar("T", bound="Client")
A = TypeVar("A", bound="AsyncClient")
logger = get_logger("TLSRequests")
class ProtocolType(str, Enum):
AUTO = "auto"
HTTP1 = "http1"
HTTP2 = "http2"
class ClientState(int, Enum):
UNOPENED = 1
OPENED = 2
CLOSED = 3
class BaseClient:
"""
A TLS-enabled HTTP client supporting advanced configuration options, including headers, cookies,
URL parameters, and proxy settings. It provides seamless HTTP/1.1 and HTTP/2 support with optional
authentication and robust redirect handling.
Attributes:
auth (Optional[AuthTypes]): Authentication options (e.g., tuples for basic auth, callable objects).
params (Optional[URLParamTypes]): URL parameters to include in requests.
headers (Optional[HeaderTypes]): Default headers for all requests.
cookies (Optional[CookieTypes]): Default cookies for all requests.
proxy (Optional[ProxyTypes]): Proxy configurations (e.g., proxy URL or instance).
timeout (Optional[float | int]): Timeout for requests, in seconds.
follow_redirects (bool): Whether to automatically follow redirects.
max_redirects (int): Maximum number of redirects allowed.
http2 (Optional[ProtocolTypes]): Specifies protocol options (e.g., 'auto', 'http1', 'http2', True, False, None).
verify (bool): Whether to verify TLS certificates.
client_identifier (Optional[TLSIdentifierTypes]): Identifier to emulate specific clients.
encoding (str): Default encoding for response decoding.
Methods:
build_request: Constructs and returns a `Request` instance with provided parameters.
prepare_headers: Merges default and custom headers for a request.
prepare_cookies: Merges default and custom cookies for a request.
prepare_params: Merges default and custom URL parameters for a request.
prepare_config: Prepares TLS and other configurations for sending a request.
close: Closes the client session and cleans up resources.
Properties:
- `session`: Returns the underlying TLS session object.
- `config`: Returns the current configuration.
- `is_closed`: Indicates if the client is closed.
- `headers`, `cookies`, `params`: Manage default headers, cookies, and parameters.
Lifecycle Management:
- Use the `BaseClient` within a context manager to ensure proper resource cleanup.
- Methods `__enter__` and `__exit__` handle opening and closing sessions automatically.
"""
def __init__(
self,
*,
auth: AuthTypes = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
proxy: ProxyTypes = None,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
max_redirects: int = DEFAULT_MAX_REDIRECTS,
http2: ProtocolTypes = DEFAULT_TLS_HTTP2,
verify: bool = True,
client_identifier: Optional[TLSIdentifierTypes] = DEFAULT_TLS_IDENTIFIER,
hooks: HookTypes = None,
encoding: str = "utf-8",
**config,
) -> None:
self._session = TLSClient.initialize()
self._config = TLSConfig.from_kwargs(**config)
self._params = URLParams(params)
self._cookies = Cookies(cookies)
self._state = ClientState.UNOPENED
self._headers = Headers(headers)
self._hooks = hooks if isinstance(hooks, dict) else {}
self.auth = auth
self.proxy = self.prepare_proxy(proxy)
self.timeout = timeout
self.follow_redirects = follow_redirects
self.max_redirects = max_redirects
self.http2 = http2
self.verify = verify
self.client_identifier = client_identifier
self.encoding = encoding
@property
def session(self) -> TLSClient:
return self._session
@property
def config(self) -> TLSConfig:
return self._config
@property
def closed(self) -> bool:
return bool(self._state == ClientState.CLOSED)
@property
def headers(self) -> Headers:
for k, v in DEFAULT_HEADERS.items():
if k not in self._headers:
self._headers[k] = v
return self._headers
@headers.setter
def headers(self, headers: HeaderTypes) -> None:
self._headers = Headers(headers)
@property
def cookies(self) -> Cookies:
return self._cookies
@cookies.setter
def cookies(self, cookies: CookieTypes) -> None:
self._cookies = Cookies(cookies)
@property
def params(self) -> URLParams:
return self._params
@params.setter
def params(self, params: URLParamTypes) -> None:
self._params = URLParams(params)
@property
def hooks(self) -> Mapping[Literal["request", "response"], list[Callable]]:
return self._hooks
@hooks.setter
def hooks(self, hooks: HookTypes) -> None:
self._hooks = self._rebuild_hooks(hooks)
def prepare_auth(
self, request: Request, auth: AuthTypes, *args, **kwargs
) -> Union[Request, Any]:
"""Build Auth Request instance"""
if isinstance(auth, tuple) and len(auth) == 2:
auth = BasicAuth(auth[0], auth[1])
return auth.build_auth(request)
if callable(auth):
return auth(request)
if isinstance(auth, Auth):
return auth.build_auth(request)
def prepare_headers(self, headers: HeaderTypes = None) -> Headers:
"""Prepare Headers"""
merged_headers = self.headers.copy()
return merged_headers.update(headers)
def prepare_cookies(self, cookies: CookieTypes = None) -> Cookies:
"""Prepare Cookies"""
merged_cookies = self.cookies.copy()
return merged_cookies.update(cookies)
def prepare_params(self, params: URLParamTypes = None) -> URLParams:
"""Prepare URL Params"""
merged_params = self.params.copy()
return merged_params.update(params)
def prepare_proxy(self, proxy: ProxyTypes = None) -> Optional[Proxy]:
if proxy is not None:
if isinstance(proxy, (bytes, str, URL, Proxy)):
return Proxy(proxy)
raise ProxyError("Invalid proxy.")
def prepare_config(self, request: Request):
"""Prepare TLS Config"""
config = self.config.copy_with(
method=request.method,
url=request.url,
body=request.read(),
headers=dict(request.headers),
cookies=[dict(name=k, value=v) for k, v in request.cookies.items()],
proxy=request.proxy.url if request.proxy else None,
timeout=request.timeout,
http2=True if self.http2 in ["auto", "http2", True, None] else False,
verify=self.verify,
tls_identifier=self.client_identifier,
)
# Set Request SessionId.
request._session_id = config.sessionId
return config
def build_request(
self,
method: str,
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
timeout: TimeoutTypes = None,
) -> Request:
"""Build Request instance"""
return Request(
method,
url,
data=data,
files=files,
json=json,
params=self.prepare_params(params),
headers=self.prepare_headers(headers),
cookies=self.prepare_cookies(cookies),
proxy=self.proxy,
timeout=timeout or self.timeout,
)
def build_hook_request(
self, request: Request, *args, **kwargs
) -> Union[Request, Any]:
request_hooks = self._rebuild_hooks(self.hooks).get("request")
if isinstance(request_hooks, Sequence):
for hook in request_hooks:
if callable(hook):
return hook(request)
def build_hook_response(
self, response: Response, *args, **kwargs
) -> Union[Response, Any]:
request_hooks = self._rebuild_hooks(self.hooks).get("response")
if isinstance(request_hooks, Sequence):
for hook in request_hooks:
if callable(hook):
return hook(response)
def _rebuild_hooks(self, hooks: HookTypes):
if isinstance(hooks, dict):
return {
str(k).lower(): [func for func in items if callable(func)]
for k, items in hooks.items()
if str(k) in ["request", "response"] and isinstance(items, Sequence)
}
def _rebuild_redirect_request(
self, request: Request, response: Response
) -> Request:
"""Rebuild Redirect Request"""
return Request(
method=self._rebuild_redirect_method(request, response),
url=self._rebuild_redirect_url(request, response),
headers=request.headers,
cookies=response.cookies,
)
def _rebuild_redirect_method(self, request: Request, response: Response):
"""Rebuild Redirect Method"""
method = request.method
if response.status_code == StatusCodes.SEE_OTHER and method != "HEAD":
method = "GET"
if response.status_code == StatusCodes.FOUND and method != "HEAD":
method = "GET"
if response.status_code == StatusCodes.MOVED_PERMANENTLY and method == "POST":
method = "GET"
return method
def _rebuild_redirect_url(self, request: Request, response: Response) -> URL:
"""Rebuild Redirect URL"""
try:
url = URL(response.headers["Location"])
except KeyError:
raise RemoteProtocolError("Invalid URL in Location headers: %s" % e)
if not url.netloc:
for missing_field in ["scheme", "host", "port"]:
setattr(url, missing_field, getattr(request.url, missing_field, ""))
# TLS error transport between HTTP/1.x -> HTTP/2
if url.scheme != request.url.scheme:
if request.url.scheme == "http":
url.scheme = request.url.scheme
else:
if self.http2 in ["auto", None]:
self.session.destroy_session(self.config.sessionId)
self.config.sessionId = str(uuid.uuid4())
else:
raise RemoteProtocolError(
"Switching remote scheme from HTTP/2 to HTTP/1 is not supported. Please initialize Client with parameter `http2` to `auto`."
)
setattr(url, "_url", None) # reset url
if not url.url:
raise RemoteProtocolError("Invalid URL in Location headers: %s" % e)
return url
def _send(
self, request: Request, *, history: list = None, start: float = None
) -> Response:
start = start or time.perf_counter()
config = self.prepare_config(request)
response = Response.from_tls_response(
self.session.request(config.to_dict()),
is_byte_response=config.isByteResponse,
)
response.request = request
response.default_encoding = self.encoding
response.elapsed = datetime.timedelta(seconds=time.perf_counter() - start)
if response.is_redirect:
response.next = self._rebuild_redirect_request(response.request, response)
if self.follow_redirects:
is_break = bool(len(history) < self.max_redirects)
if not is_break:
raise TooManyRedirects("Too many redirects.")
while is_break:
history.append(response)
return self._send(response.next, history=history, start=start)
response.history = history
return response
def close(self) -> None:
"""Close TLS Client session."""
self.session.destroy_session(self.config.sessionId)
self._state = ClientState.CLOSED
def __enter__(self: T) -> T:
if self._state == ClientState.OPENED:
raise RuntimeError(
"It is not possible to open a client instance more than once."
)
if self._state == ClientState.CLOSED:
raise RuntimeError(
"The client instance cannot be reopened after it has been closed."
)
self._state = ClientState.OPENED
return self
def __exit__(self, *args, **kwargs) -> None:
self.close()
class Client(BaseClient):
"""
An HTTP client with advanced features such as connection pooling, HTTP/2 support,
automatic redirects, and cookie persistence.
This client is thread-safe and can be shared between threads for efficient HTTP
interactions in multi-threaded applications.
Usage:
```python
>>> with tls_requests.AsyncClient(http2='auto', follow_redirects=True) as client:
response = client.get('https://httpbin.org/get')
response.raise_for_status()
>>> response
<Response [200]>
```
Parameters:
- Inherits all parameters and configurations from `tls_requests.BaseClient`.
"""
def request(
self,
method: str,
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
):
"""
Constructs and sends an HTTP request.
This method builds a `Request` object based on the given parameters, sends
it using the configured client, and returns the server's response.
Parameters:
- **method** (str): HTTP method to use (e.g., `"GET"`, `"POST"`).
- **url** (URLTypes): The URL to send the request to.
- **params** (optional): Query parameters to include in the request URL.
- **data** (optional): Form data to include in the request body.
- **json** (optional): A JSON serializable object to include in the request body.
- **headers** (optional): Custom headers to include in the request.
- **cookies** (optional): Cookies to include with the request.
- **files** (optional): Files to upload in a multipart request.
- **auth** (optional): Authentication credentials or handler.
- **timeout** (optional): Timeout configuration for the request.
- **follow_redirects** (optional): Whether to follow HTTP redirects.
Returns:
- **Response**: The client's response to the HTTP request.
Usage:
```python
>>> r = client.request('GET', 'https://httpbin.org/get')
>>> r
<Response [200]>
```
"""
request = self.build_request(
method=method,
url=url,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
)
return self.send(request, auth=auth, follow_redirects=follow_redirects)
def send(
self,
request: Request,
*,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
):
if self._state == ClientState.CLOSED:
raise RuntimeError("Cannot send a request, as the client has been closed.")
self._state = ClientState.OPENED
for fn in [self.prepare_auth, self.build_hook_request]:
request_ = fn(request, auth or self.auth, follow_redirects)
if isinstance(request_, Request):
request = request_
self.follow_redirects = follow_redirects
response = self._send(request, start=time.perf_counter(), history=[])
if self.hooks.get("response"):
response_ = self.build_hook_response(response)
if isinstance(response_, Response):
response = response_
else:
response.read()
response.close()
return response
def get(
self,
url: URLTypes,
*,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
):
"""
Send a `GET` request.
**Parameters**: See `tls_requests.request`.
"""
return self.request(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
def options(
self,
url: URLTypes,
*,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send an `OPTIONS` request.
**Parameters**: See `tls_requests.request`.
"""
return self.request(
"OPTIONS",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
def head(
self,
url: URLTypes,
*,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `HEAD` request.
**Parameters**: See `tls_requests.request`.
"""
return self.request(
"HEAD",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
def post(
self,
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `POST` request.
**Parameters**: See `tls_requests.request`.
"""
return self.request(
"POST",
url,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
def put(
self,
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `PUT` request.
**Parameters**: See `tls_requests.request`.
"""
return self.request(
"PUT",
url,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
def patch(
self,
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `PATCH` request.
**Parameters**: See `tls_requests.request`.
"""
return self.request(
"PATCH",
url,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
def delete(
self,
url: URLTypes,
*,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `DELETE` request.
**Parameters**: See `tls_requests.request`.
"""
return self.request(
"DELETE",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
class AsyncClient(BaseClient):
"""
An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,
cookie persistence, etc.
It can be shared between tasks.
Usage:
```python
>>> import asyncio
>>> async def fetch(url: str, params: URLParamTypes = None)
async with tls_requests.AsyncClient(http2='auto', follow_redirects=True) as client:
response = await client.get(url, params=params)
response.raise_for_status()
return response
>>> response = asyncio.run(fetch('https://httpbin.org/get'))
```
**Parameters:** See `tls_requests.BaseClient`.
"""
async def request(
self,
method: str,
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""Async Request"""
request = self.build_request(
method=method,
url=url,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
)
return await self.send(request, auth=auth, follow_redirects=follow_redirects)
async def get(
self,
url: URLTypes,
*,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `GET` request.
**Parameters**: See `tls_requests.request`.
"""
return await self.request(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
async def options(
self,
url: URLTypes,
*,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send an `OPTIONS` request.
**Parameters**: See `tls_requests.request`.
"""
return await self.request(
"OPTIONS",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
async def head(
self,
url: URLTypes,
*,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `HEAD` request.
**Parameters**: See `tls_requests.request`.
"""
return await self.request(
"HEAD",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
async def post(
self,
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `POST` request.
**Parameters**: See `tls_requests.request`.
"""
return await self.request(
"POST",
url,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
async def put(
self,
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `PUT` request.
**Parameters**: See `tls_requests.request`.
"""
return await self.request(
"PUT",
url,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
async def patch(
self,
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `PATCH` request.
**Parameters**: See `tls_requests.request`.
"""
return await self.request(
"PATCH",
url,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
async def delete(
self,
url: URLTypes,
*,
params: URLParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
timeout: TimeoutTypes = DEFAULT_TIMEOUT,
) -> Response:
"""
Send a `DELETE` request.
**Parameters**: See `tls_requests.request`.
"""
return await self.request(
"DELETE",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
)
async def send(
self,
request: Request,
*,
stream: bool = False,
auth: AuthTypes = None,
follow_redirects: bool = DEFAULT_FOLLOW_REDIRECTS,
) -> Response:
if self._state == ClientState.CLOSED:
raise RuntimeError("Cannot send a request, as the client has been closed.")
self._state = ClientState.OPENED
for fn in [self.prepare_auth, self.build_hook_request]:
request_ = fn(request, auth or self.auth, follow_redirects)
if isinstance(request_, Request):
request = request_
self.follow_redirects = follow_redirects
response = await self._send(request, start=time.perf_counter(), history=[])
if self.hooks.get("response"):
response_ = self.build_hook_response(response)
if isinstance(response_, Response):
response = response_
else:
await response.aread()
await response.aclose()
return response
async def _send(
self, request: Request, *, history: list = None, start: float = None
) -> Response:
start = start or time.perf_counter()
config = self.prepare_config(request)
response = Response.from_tls_response(
await self.session.arequest(config.to_dict()),
is_byte_response=config.isByteResponse,
)
response.request = request