gpt4 book ai didi

python - 如何创建一个通过 items() 返回重复值的类 dict 对象

转载 作者:行者123 更新时间:2023-12-03 20:02:18 25 4
gpt4 key购买 nike

框架
我正在使用 hyper生成 HTTP/2 流量的框架。在生成请求和响应时,我目前正在使用 hyper.HTTP20Connection.requesth2.H2Connection.send_headers分别发送 HTTP/2 请求和响应。
我的要求
我需要能够发送带有重复字段的 HTTP/2 请求和响应。例如,这里是一个 YAML 指定的请求,它包含两个 x-test-duplicate领域:

  headers:
fields:
- [ :method, GET, equal ]
- [ :scheme, https, equal ]
- [ :authority, example.data.com, equal ]
- [ :path, '/a/path?q=3', equal ]
- [ Accept, '*/*' ]
- [ Accept-Language, en-us ]
- [ Accept-Encoding, gzip ]
- [ x-test-duplicate, first ]
- [ x-test-duplicate, second ]
- [ Content-Length, "0" ]
请注意,根据 HTTP/2 规范,这是明确允许的。参见示例 RFC 7541 section 2.3.2 :

The dynamic table can contain duplicate entries (i.e., entries withthe same name and same value). Therefore, duplicate entries MUST NOTbe treated as an error by a decoder.


我的问题
问题是,虽然 h2.H2Connection.send_headers正确处理可包含重复字段的元组迭代(例如 (("name1", "value1"), ("name2", "value2"), ("name1", "another_value")) ), hyper.HTTP20Connection.request需要一个字典,当然,它不是为重复键设计的。文档不清楚 headers 上的类型要求, 但在 HTTP20Connection:request, line 261 的源代码中, items()被取消。如果我传递一个可迭代的元组,我会得到 AttributeError: 'tuple' object has no attribute 'items' .请注意这是多么可悲:超框架强制用户传入一个不允许重复的字典,然后立即通过 items() 将该字典转换为可迭代的元组,后者将允许重复字段。如果只需要一个可迭代的元组开始,比如 h2 的接口(interface),我就不会有这个问题。
我的问题
我提交了问题 437在关于这个限制的 super github 项目中。与此同时,我希望我能解决这个问题。我有一个表示具有重复字段的 HTTP/2 header 的元组的可迭代。我可以以某种方式将其包装在一个对象中,这样当 HTTP20Connection:request, line 261来电 items()反对它,它只是返回元组的迭代?

最佳答案

Python 通常使用 EmailMessage例如(docs)。

The EmailMessage dictionary-like interface is indexed by the header names, which must be ASCII values. The values of the dictionary are strings with some extra methods. Headers are stored and returned in case-preserving form, but field names are matched case-insensitively. Unlike a real dict, there is an ordering to the keys, and there can be duplicate keys. Additional methods are provided for working with headers that have duplicate keys.


在基本用法中,您可以使用 EmailMessage.add_header 设置项目。并使用 EmailMessage.items 检索它们.您可以将有效负载留空。
>>> from email.message import EmailMessage
>>> headers = EmailMessage()
>>> headers.add_header("x-test-duplicate", "first")
>>> headers.add_header("x-test-duplicate", "second")
>>> headers.items()
[('x-test-duplicate', 'first'), ('x-test-duplicate', 'second')]
这是 urllib 中的实战测试本身,其中 uses the same class for HTTPResponse headers .
滚动您自己的 multidict 或使用简单的对列表的优点是您将获得 header 的正确行为(RFC 5322 和 RFC 6532 样式字段名称和值),例如不区分大小写:
>>> headers.add_header("aBc", "val1")
>>> headers.add_header("AbC", "val2")
>>> headers.get_all("ABC")
['val1', 'val2']

关于python - 如何创建一个通过 items() 返回重复值的类 dict 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65604353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com