My HTTP client uses the Python requests library to access an API proxied by CloudFlare. The client converts the numerical response status code to an HTTPStatus enum instance. Simplified ...
import requests
from http import HTTPStatus
url = ...
response = requests.get(url)
status = HTTPStatus(response.status_code)
The CloudFlare proxy service can return some unofficial 5xx HTTP status codes: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#CloudFlare. These cause HTTPStatus to raise a ValueError because codes such as 522 (Connection Timed Out) are not members of the HTTPStatus enum defined in Python's lib/http/__init__.py.
How can I add the unoffical CloudFlare status codes to the HTTPStatus enum? Or, how can I load the HTTPStatus enum members into some other enum along with the unoffical CloudFlare status codes?
The Python 3.5 Enum documentation, https://docs.python.org/3/library/enum.html, describes restrictions that have thwarted me thus far.
Section 8.13.9: Subclassing an enumeration is allowed only if the enumeration does not define any members.
Section 8.13.14.2: The most interesting thing about
Enummembers is that they are singletons.EnumMetacreates them all while it is creating theEnumclass itself, and then puts a custom__new__()in place to ensure that no new ones are ever instantiated by returning only the existing member instances.
The new aenum library1 has an extend_enum function that is capable of adding new members to an existing enumeration.
Example usage:
import aenum
from http import HTTPStatus
aenum.extend_enum(HTTPStatus, 'BAD_SPAM', 513, 'Too greasy')
aenum.extend_enum(HTTPStatus, 'BAD_EGGS', 514, 'Too green')
1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With