Skip to content

# Http status code

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, 2025 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.

## `HTTPStatusCode`

Provides an interface for the extration of the HTTP status code.

Source code in `PyFunceble/query/http_status_code.py`

     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

    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
        requester: Optional[Requester] = 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()
            self.requester = Requester(config=PyFunceble.storage.CONFIGURATION)

        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 = self.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 (
                self.requester.exceptions.RequestException,
                self.requester.exceptions.InvalidSchema,
                self.requester.exceptions.InvalidURL,
                self.requester.exceptions.MissingSchema,
                socket.timeout,
                self.requester.urllib3_exceptions.InvalidHeader,
            ):
                pass

            return self.STD_UNKNOWN_STATUS_CODE

### `allow_redirects` `property` `writable`

Provides the current state of the :code:`_allow_redirects` attribute.

### `subject` `property` `writable`

Provides the current state of the :code:`_subject` attribute.

### `timeout` `property` `writable`

Provides the current state of the :code:`_timeout` attribute.

### `verify_certificate` `property` `writable`

Provides the current state of the :code:`verify_certificate` attribute.

### `ensure_subject_is_given(func)`

Ensures that the subject is given before running the decorated method.

Raises:

Type | Description
--- | ---
`TypeError` | If the subject is not a string.

Source code in `PyFunceble/query/http_status_code.py`

    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126

    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

### `get_status_code()`

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.

Source code in `PyFunceble/query/http_status_code.py`

    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

    @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 = self.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 (
            self.requester.exceptions.RequestException,
            self.requester.exceptions.InvalidSchema,
            self.requester.exceptions.InvalidURL,
            self.requester.exceptions.MissingSchema,
            socket.timeout,
            self.requester.urllib3_exceptions.InvalidHeader,
        ):
            pass

        return self.STD_UNKNOWN_STATUS_CODE

### `guess_and_set_timeout()`

Tries to guess and set the timeout from the configuration.

Source code in `PyFunceble/query/http_status_code.py`

    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223

    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

### `guess_and_set_verify_certificate()`

Tries to guess and set the :code:`verify_certificate` attribute.

Source code in `PyFunceble/query/http_status_code.py`

    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274

    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

### `set_allow_redirects(value)`

Sets the value of the :code:`verify_certificate` variable.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `bool` | The value to set. | required

Source code in `PyFunceble/query/http_status_code.py`

    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311

    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

### `set_subject(value)`

Sets the subject to work with.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `str` | The subject to set. | required

Source code in `PyFunceble/query/http_status_code.py`

    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168

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

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

        self.subject = value

        return self

### `set_timeout(value)`

Sets the timeout to apply.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `Union[float, int]` | The timeout to apply. | required

Source code in `PyFunceble/query/http_status_code.py`

    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211

    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

### `set_verify_certificate(value)`

Sets the value of the :code:`verify_certificate` variable.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `bool` | The value to set. | required

Source code in `PyFunceble/query/http_status_code.py`

    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260

    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