File: requester.py

package info (click to toggle)
python-pyfunceble 4.2.29.dev-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,108 kB
  • sloc: python: 27,413; sh: 142; makefile: 27
file content (600 lines) | stat: -rw-r--r-- 18,028 bytes parent folder | download
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
"""
The tool to check the availability or syntax of domain, IP or URL.

::


    ██████╗ ██╗   ██╗███████╗██╗   ██╗███╗   ██╗ ██████╗███████╗██████╗ ██╗     ███████╗
    ██╔══██╗╚██╗ ██╔╝██╔════╝██║   ██║████╗  ██║██╔════╝██╔════╝██╔══██╗██║     ██╔════╝
    ██████╔╝ ╚████╔╝ █████╗  ██║   ██║██╔██╗ ██║██║     █████╗  ██████╔╝██║     █████╗
    ██╔═══╝   ╚██╔╝  ██╔══╝  ██║   ██║██║╚██╗██║██║     ██╔══╝  ██╔══██╗██║     ██╔══╝
    ██║        ██║   ██║     ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
    ╚═╝        ╚═╝   ╚═╝      ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝

Provides our own requests handler

Author:
    Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom

Special thanks:
    https://pyfunceble.github.io/#/special-thanks

Contributors:
    https://pyfunceble.github.io/#/contributors

Project link:
    https://github.com/funilrys/PyFunceble

Project documentation:
    https://docs.pyfunceble.com

Project homepage:
    https://pyfunceble.github.io/

License:
::


    Copyright 2017, 2018, 2019, 2020, 2022, 2023, 2024 Nissar Chababy

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

import functools
import logging
import warnings
from typing import Optional, Union

import requests
import requests.exceptions
import urllib3.exceptions

import PyFunceble.facility
import PyFunceble.storage
from PyFunceble.dataset.user_agent import UserAgentDataset
from PyFunceble.query.dns.query_tool import DNSQueryTool
from PyFunceble.query.requests.adapter.http import RequestHTTPAdapter
from PyFunceble.query.requests.adapter.https import RequestHTTPSAdapter


class Requester:
    """
    Provides our very own requests handler.

    :param int max_retries:
        Optional, The maximum number of retries to perform.
    :param bool verify_certificate:
        Optional, Should we verify and validate the SSL/TLS certificate ?
    :param float timeout:
        Optional, The timeout to apply to the query.
    :param int max_redirects:
        Optional, The maximum number of redirects to allow.
    :param dns_query_tool:
        Optional, The DNS Query tool to use.
    :param proxy_pattern:
        Optional, The proxy pattern to apply to each query.

        Expected format:

            ::
                {
                    "global": {
                        # Everything under global will be used as default if no
                        # rule matched.

                        "http": "str" ## HTTP_PROXY
                        "https": "str" ## HTTPS_PROXY
                    },
                    "rules":[
                        # A set/list of rules to work with.

                        {
                            "http": "str" ## HTTP_PROXY when TLD is matched.
                            "https": "str" ## HTTPS_PROXY when TLD is matched.
                            "tld": [
                                "str",
                                "str",
                                str
                            ]
                        },
                        {
                            "http": "str" ## HTTP_PROXY when TLD is matched.
                            "https": "str" ## HTTPS_PROXY when TLD is matched.
                            "tld": [
                                "str",
                                "str"
                            ]
                        },
                    ]
                }
    """

    STD_VERIFY_CERTIFICATE: bool = False
    STD_TIMEOUT: float = 3.0
    STD_MAX_RETRIES: int = 3

    urllib3_exceptions = urllib3.exceptions
    exceptions = requests.exceptions

    _timeout: float = 5.0
    _max_retries: int = 3
    _verify_certificate: bool = True
    _max_redirects: int = 60
    _proxy_pattern: dict = {}

    session: Optional[requests.Session] = None
    dns_query_tool: Optional[DNSQueryTool] = None

    def __init__(
        self,
        *,
        max_retries: Optional[int] = None,
        verify_certificate: Optional[bool] = None,
        timeout: Optional[float] = None,
        max_redirects: Optional[int] = None,
        dns_query_tool: Optional[DNSQueryTool] = None,
        proxy_pattern: Optional[dict] = None,
    ) -> None:
        if max_retries is not None:
            self.max_retries = max_retries
        else:
            self.guess_and_set_max_retries()

        if verify_certificate is not None:
            self.verify_certificate = verify_certificate
        else:
            self.guess_and_set_verify_certificate()

        if timeout is not None:
            self.timeout = timeout
        else:
            self.guess_and_set_timeout()

        if max_redirects is not None:
            self.max_redirects = max_redirects

        if dns_query_tool is not None:
            self.dns_query_tool = dns_query_tool
        else:
            self.dns_query_tool = DNSQueryTool()

        if proxy_pattern is not None:
            self.proxy_pattern = proxy_pattern
        else:
            self.guess_and_set_proxy_pattern()

        self.session = self.get_session()

        warnings.simplefilter("ignore", urllib3.exceptions.InsecureRequestWarning)
        logging.getLogger("requests.packages.urllib3").setLevel(logging.CRITICAL)
        logging.getLogger("urllib3").setLevel(logging.CRITICAL)

    def recreate_session(func):  # pylint: disable=no-self-argument
        """
        Recreate a new session after executing the decorated method.
        """

        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            result = func(self, *args, **kwargs)  # pylint: disable=not-callable

            if hasattr(self, "session") and isinstance(self.session, requests.Session):
                self.session = self.get_session()

            return result

        return wrapper

    def request_factory(verb: str):  # pylint: disable=no-self-argument
        """
        Provides a universal request factory.

        :param verb:
            The HTTP Verb to apply.
        """

        def request_method(func):
            @functools.wraps(func)
            def wrapper(self, *args, **kwargs):
                # pylint: disable=no-member
                PyFunceble.facility.Logger.debug(
                    "Started %r request to %r with %r",
                    verb.upper(),
                    args[0],
                    kwargs,
                )
                req = getattr(self.session, verb.lower())(*args, **kwargs)

                PyFunceble.facility.Logger.debug(
                    "Finished %r request to %r with %r",
                    verb.upper(),
                    args[0],
                    kwargs,
                )

                return req

            return wrapper

        return request_method

    @property
    def max_retries(self) -> int:
        """
        Provides the current state of the :code:`_max_retries` attribute.
        """

        return self._max_retries

    @max_retries.setter
    @recreate_session
    def max_retries(self, value: int) -> None:
        """
        Sets the max retries value to apply to all subsequent requests.

        :param value:
            The value to set.

        :raise TypeError:
            When the given :code:`value` is not a :py:class:`int`.
        :raise ValueError:
            When the given :code:`value` is less than :code:`1`.
        """

        if not isinstance(value, int):
            raise TypeError(f"<value> should be {int}, {type(value)} given.")

        if value < 0:
            raise ValueError(f"<value> ({value!r}) should be positive.")

        self._max_retries = value

    def set_max_retries(self, value: int) -> "Requester":
        """
        Sets the max retries value to apply to all subsequent requests.

        :param value:
            The value to set.
        """

        self.max_retries = value

        return self

    def guess_and_set_max_retries(self) -> "Requester":
        """
        Try to guess the value from the configuration and set it.
        """

        if PyFunceble.facility.ConfigLoader.is_already_loaded() and bool(
            PyFunceble.storage.CONFIGURATION.max_http_retries
        ):
            self.set_max_retries(
                bool(PyFunceble.storage.CONFIGURATION.max_http_retries)
            )
        else:
            self.set_max_retries(self.STD_MAX_RETRIES)

        return self

    @property
    def max_redirects(self) -> int:
        """
        Provides the current state of the :code:`_max_redirects` attribute.
        """

        return self._max_redirects

    @max_redirects.setter
    @recreate_session
    def max_redirects(self, value: int) -> None:
        """
        Sets the max redirects value to apply to all subsequent requests.

        :param value:
            The value to set.

        :raise TypeError:
            When the given :code:`value` is not a :py:class:`int`.
        :raise ValueError:
            When the given :code:`value` is less than :code:`1`.
        """

        if not isinstance(value, int):
            raise TypeError(f"<value> should be {int}, {type(value)} given.")

        if value < 1:
            raise ValueError(f"<value> ({value!r}) should not be less than 1.")

        self._max_redirects = value

    def set_max_redirects(self, value: int) -> "Requester":
        """
        Sets the max redirects value to apply to all subsequent requests.

        :param value:
            The value to set.
        """

        self.max_redirects = value

        return self

    @property
    def verify_certificate(self) -> bool:
        """
        Provides the current state of the :code:`_verify_certificate` attribute.
        """

        return self._verify_certificate

    @verify_certificate.setter
    @recreate_session
    def verify_certificate(self, value: bool) -> None:
        """
        Enable or disables the certificate validation.

        :param value:
            The value to set.

        :raise TypeError:
            When the given :code:`value` is not a :py:class`bool`.
        """

        if not isinstance(value, bool):
            raise TypeError(f"<value> shoule be {bool}, {type(value)} given.")

        self._verify_certificate = value

    def set_verify_certificate(self, value: bool) -> "Requester":
        """
        Enable or disables the certificate validation.

        :param value:
            The value to set.
        """

        self.verify_certificate = value

        return self

    def guess_and_set_verify_certificate(self) -> "Requester":
        """
        Try to guess the value from the configuration and set it.
        """

        if PyFunceble.facility.ConfigLoader.is_already_loaded() and bool(
            PyFunceble.storage.CONFIGURATION.verify_ssl_certificate
        ):
            self.set_verify_certificate(
                bool(PyFunceble.storage.CONFIGURATION.verify_ssl_certificate)
            )
        else:
            self.set_verify_certificate(self.STD_VERIFY_CERTIFICATE)

        return self

    @property
    def timeout(self) -> float:
        """
        Provides the current state of the :code:`_timeout` attribute.
        """

        return self._timeout

    @timeout.setter
    @recreate_session
    def timeout(self, value: Union[int, float]) -> None:
        """
        Enable or disables the certificate validation.

        :param value:
            The value to set.

        :raise TypeError:
            When the given :code:`value` is not a :py:class`int` nor
            :py:class:`float`.
        :raise ValueError:
            Whent the given :code:`value` is less than `1`.
        """

        if not isinstance(value, (int, float)):
            raise TypeError(f"<value> shoule be {int} or {float}, {type(value)} given.")

        if value < 0:
            raise ValueError("<value> should not be less than 0.")

        self._timeout = float(value)

    def set_timeout(self, value: Union[int, float]) -> "Requester":
        """
        Enable or disables the certificate validation.

        :param value:
            The value to set.
        """

        self.timeout = value

        return self

    def guess_and_set_timeout(self) -> "Requester":
        """
        Try to guess the value from the configuration and set it.
        """

        if PyFunceble.facility.ConfigLoader.is_already_loaded() and bool(
            PyFunceble.storage.CONFIGURATION.lookup.timeout
        ):
            self.set_timeout(PyFunceble.storage.CONFIGURATION.lookup.timeout)
        else:
            self.set_timeout(self.STD_TIMEOUT)

        return self

    @property
    def proxy_pattern(self) -> Optional[dict]:
        """
        Provides the current state of the :code:`_proxy_pattern` attribute.
        """

        return self._proxy_pattern

    @proxy_pattern.setter
    @recreate_session
    def proxy_pattern(self, value: dict) -> None:
        """
        Overwrite the proxy pattern to use.

        :param value:
            The value to set.

        :raise TypeError:
            When the given :code:`value` is not a :py:class`dict`.
        """

        if not isinstance(value, dict):
            raise TypeError(f"<value> shoule be {dict}, {type(value)} given.")

        self._proxy_pattern = value

    def set_proxy_pattern(self, value: dict) -> "Requester":
        """
        Overwrite the proxy pattern.

        :param value:
            The value to set.
        """

        self.proxy_pattern = value

        return self

    def guess_and_set_proxy_pattern(self) -> "Requester":
        """
        Try to guess the value from the configuration and set it.
        """

        if PyFunceble.facility.ConfigLoader.is_already_loaded() and bool(
            PyFunceble.storage.CONFIGURATION.proxy
        ):
            self.set_proxy_pattern(PyFunceble.storage.CONFIGURATION.proxy)
        else:
            self.set_proxy_pattern({})

        return self

    def guess_all_settings(self) -> "Requester":
        """
        Try to guess all settings.
        """

        to_ignore = ["guess_all_settings"]

        for method in dir(self):
            if method in to_ignore or not method.startswith("guess_"):
                continue

            getattr(self, method)()

        return self

    def get_verify_certificate(self) -> bool:
        """
        Provides the current value of the certificate validation.
        """

        return self.verify_certificate

    def get_timeout(self) -> float:
        """
        Provides the currently set timetout.
        """

        return self.timeout

    def get_session(self) -> requests.Session:
        """
        Provides a new session.
        """

        session = requests.Session()

        session.verify = self.verify_certificate
        session.max_redirects = self.max_redirects
        session.mount(
            "https://",
            RequestHTTPSAdapter(
                max_retries=self.max_retries,
                timeout=self.timeout,
                dns_query_tool=self.dns_query_tool,
                proxy_pattern=self.proxy_pattern,
            ),
        )
        session.mount(
            "http://",
            RequestHTTPAdapter(
                max_retries=self.max_retries,
                timeout=self.timeout,
                dns_query_tool=self.dns_query_tool,
                proxy_pattern=self.proxy_pattern,
            ),
        )

        custom_headers = {"User-Agent": UserAgentDataset().get_latest()}

        session.headers.update(custom_headers)

        return session

    @request_factory("GET")
    def get(self, *args, **kwargs) -> requests.Response:
        """
        Sends a GET request and get its response.
        """

    @request_factory("OPTIONS")
    def options(self, *args, **kwargs) -> requests.Response:
        """
        Sends am OPTIONS request and get its response.
        """

    @request_factory("HEAD")
    def head(self, *args, **kwargs) -> requests.Response:
        """
        Sends a HEAD request and get its response.
        """

    @request_factory("POST")
    def post(self, *args, **kwargs) -> requests.Response:
        """
        Sends a POST request and get its response.
        """

    @request_factory("PUT")
    def put(self, *args, **kwargs) -> requests.Response:
        """
        Sends a PUT request and get its response.
        """

    @request_factory("PATCH")
    def patch(self, *args, **kwargs) -> requests.Response:
        """
        Sends a PATCH request and get its response.
        """

    @request_factory("DELETE")
    def delete(self, *args, **kwargs) -> requests.Response:
        """
        Sends a DELETE request and get its response.
        """