如何在Python 3.5中向HTTPStatus添加自定义代码? [英] How to add custom codes to HTTPStatus in Python 3.5?

查看:136
本文介绍了如何在Python 3.5中向HTTPStatus添加自定义代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTTP客户端使用Python requests 库访问由CloudFlare代理的API。客户端将数值响应状态代码转换为 HTTPStatus 枚举实例。简化...

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)

CloudFlare代理服务可以返回一些非官方的5xx HTTP状态代码: https:// en。 wikipedia.org/wiki/List_of_HTTP_status_codes#CloudFlare 。这些导致 HTTPStatus 引发 ValueError ,因为诸如522(连接超时)之类的代码不是<$的成员。在Python的 lib / http / __ init __。py 中定义的c $ c> HTTPStatus 枚举。

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.

如何将非官方的CloudFlare状态代码添加到 HTTPStatus 枚举中?或者,如何将 HTTPStatus 枚举成员与非官方的CloudFlare状态代码一起加载到其他枚举中?

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?

Python 3.5 枚举文档, https: //docs.python.org/3/library/enum.html ,介绍了到目前为止阻碍我的限制。

The Python 3.5 Enum documentation, https://docs.python.org/3/library/enum.html, describes restrictions that have thwarted me thus far.


第8.13.9节:只有在
枚举未定义任何成员的情况下,才允许对枚举进行子类化。

Section 8.13.9: Subclassing an enumeration is allowed only if the enumeration does not define any members.

第8.13.14.2节:关于枚举成员是
,它们是单例。 EnumMeta 会全部创建它们,而
会自己创建 Enum 类,然后放置自定义 __ new __()
到位,通过仅返回现有成员实例的
来确保不会实例化任何新实例。

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.


推荐答案

新的 aenum库 1 具有 extend_enum 函数,该函数能够将新成员添加到现有枚举中。

The new aenum library1 has an extend_enum function that is capable of adding new members to an existing enumeration.

示例用法:

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 披露:我是< a href = https://docs.python.org/3/library/enum.html rel = nofollow noreferrer> Python stdlib 枚举 enum34 移植高级枚举( aenum 库。


1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

这篇关于如何在Python 3.5中向HTTPStatus添加自定义代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆