File: http_status_code.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 (375 lines) | stat: -rw-r--r-- 11,763 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
"""
The tool to check the availability or syntax of domain, IP or URL.

::


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

Provides our interface for getting the status code of a given subject.

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 socket
from typing import Optional, Union

import PyFunceble.facility
import PyFunceble.factory
import PyFunceble.storage
from PyFunceble.converter.url2netloc import Url2Netloc


class HTTPStatusCode:
    """
    Provides an interface for the extration of the HTTP status code.
    """

    STD_UNKNOWN_STATUS_CODE: int = 99999999
    STD_TIMEOUT: float = 5.0
    STD_VERIFY_CERTIFICATE: bool = True
    STD_ALLOW_REDIRECTS: bool = False

    _subject: Optional[str] = None
    _timeout: float = 5.0
    _verify_certificate: bool = True
    _allow_redirects: bool = False
    _url2netloc: Optional[Url2Netloc] = None

    def __init__(
        self,
        subject: Optional[str] = None,
        *,
        timeout: Optional[float] = None,
        verify_certificate: Optional[bool] = None,
        allow_redirects: Optional[bool] = None,
    ) -> None:
        if subject is not None:
            self.subject = subject

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

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

        if allow_redirects is not None:
            self.allow_redirects = allow_redirects
        else:
            self.allow_redirects = self.STD_ALLOW_REDIRECTS

        self._url2netloc = Url2Netloc()

    def ensure_subject_is_given(func):  # pylint: disable=no-self-argument
        """
        Ensures that the subject is given before running the decorated method.

        :raise TypeError:
            If the subject is not a string.
        """

        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            if not isinstance(self.subject, str):
                raise TypeError(
                    f"<self.subject> should be {str}, {type(self.subject)} given."
                )

            return func(self, *args, **kwargs)  # pylint: disable=not-callable

        return wrapper

    @property
    def subject(self) -> Optional[str]:
        """
        Provides the current state of the :code:`_subject` attribute.
        """

        return self._subject

    @subject.setter
    def subject(self, value: str) -> None:
        """
        Sets the subject to work with.

        :param value:
            The subject to set.

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

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

        if not value:
            raise ValueError("<value> should not be empty.")

        self._subject = value

    def set_subject(self, value: str) -> "HTTPStatusCode":
        """
        Sets the subject to work with.

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

        self.subject = value

        return self

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

        return self._timeout

    @timeout.setter
    def timeout(self, value: Union[float, int]) -> None:
        """
        Sets the timeout to apply.

        :param value:
            The timeout to apply.

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

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

        if value < 0:
            raise ValueError(f"<value> ({value!r}) shouldn't be less than 0.")

        self._timeout = float(value)

    def set_timeout(self, value: Union[float, int]) -> "HTTPStatusCode":
        """
        Sets the timeout to apply.

        :param value:
            The timeout to apply.
        """

        self.timeout = value

        return self

    def guess_and_set_timeout(self) -> "HTTPStatusCode":
        """
        Tries to guess and set the timeout from the configuration.
        """

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

        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
    def verify_certificate(self, value: bool) -> None:
        """
        Sets the value of the :code:`verify_certificate` variable.

        :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> should be {bool}, {type(value)} given.")

        self._verify_certificate = value

    def set_verify_certificate(self, value: bool) -> "HTTPStatusCode":
        """
        Sets the value of the :code:`verify_certificate` variable.

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

        self.verify_certificate = value

        return self

    def guess_and_set_verify_certificate(self) -> "HTTPStatusCode":
        """
        Tries to guess and set the :code:`verify_certificate` attribute.
        """

        if PyFunceble.facility.ConfigLoader.is_already_loaded():
            self.verify_certificate = bool(
                PyFunceble.storage.CONFIGURATION["verify_ssl_certificate"]
            )
        else:
            self.verify_certificate = self.STD_VERIFY_CERTIFICATE

        return self

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

        return self._allow_redirects

    @allow_redirects.setter
    def allow_redirects(self, value: bool) -> None:
        """
        Sets the value of the :code:`verify_certificate` variable.

        :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> should be {bool}, {type(value)} given.")

        self._allow_redirects = value

    def set_allow_redirects(self, value: bool) -> "HTTPStatusCode":
        """
        Sets the value of the :code:`verify_certificate` variable.

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

        self.allow_redirects = value

        return self

    @ensure_subject_is_given
    def get_status_code(self) -> int:
        """
        Provides the status code.

        .. note::
            The HTTP status code provided will differs regarding the following
            conditions.

            Assuming, that :code:`allow_redirects` is set to :py:class:`False`,
            you will be provided the following:

                - :code:`http://example.org (302) -> https://example.org (200) ===> 200`

                - :code:`http://example.org (302) -> https://test.example.rog (200) ===> 302`

                - :code:`http://example.org (302) -> https://test.example.org (301) -> https://example.org (200) ===> 302

            On the other site if the :code:`allow_redirects` property is set to
            :py:class:`True`, this method will provide the status of the
            last one in the redirection order.

            In case of any error, this method will provide the default one.
        """  # pylint: disable=line-too-long

        try:
            req = PyFunceble.factory.Requester.get(
                self.subject,
                timeout=self.timeout,
                verify=self.verify_certificate,
                allow_redirects=True,
            )

            first_origin = self._url2netloc.set_data_to_convert(
                self.subject
            ).get_converted()

            if len(req.history) > 1:
                final_origin = self._url2netloc.set_data_to_convert(
                    req.history[1].url
                ).get_converted()
            else:
                final_origin = self._url2netloc.set_data_to_convert(
                    req.url
                ).get_converted()

            if (
                not self.allow_redirects
                and first_origin != final_origin
                and req.history
            ):
                return req.history[0].status_code

            return req.status_code
        except (
            PyFunceble.factory.Requester.exceptions.RequestException,
            PyFunceble.factory.Requester.exceptions.InvalidSchema,
            PyFunceble.factory.Requester.exceptions.InvalidURL,
            PyFunceble.factory.Requester.exceptions.MissingSchema,
            socket.timeout,
            PyFunceble.factory.Requester.urllib3_exceptions.InvalidHeader,
        ):
            pass

        return self.STD_UNKNOWN_STATUS_CODE