Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom codes to HTTPStatus in Python 3.5?

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 Enum members is that they are singletons. EnumMeta creates them all while it is creating the Enum class 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.

like image 978
Joel Shprentz Avatar asked May 24 '26 05:05

Joel Shprentz


1 Answers

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.

like image 185
Ethan Furman Avatar answered May 26 '26 20:05

Ethan Furman