63
63
64
64
65
65
class Headers :
66
- __slots__ = ['raw_items' ]
67
-
68
- def __init__ (self , raw_items ):
69
- self .raw_items = raw_items
66
+ """
67
+ A list-like interface that allows iterating over headers as byte-pairs
68
+ of (lowercased-name, value).
69
+
70
+ Internally we actually store the representation as three-tuples,
71
+ including both the raw original casing, in order to preserve casing
72
+ over-the-wire, and the lowercased name, for case-insensitive comparisions.
73
+
74
+ r = Request(
75
+ method="GET",
76
+ target="/",
77
+ headers=[("Host", "example.org"), ("Connection", "keep-alive")],
78
+ http_version="1.1",
79
+ )
80
+ assert r.headers == [
81
+ (b"host", b"example.org"),
82
+ (b"connection", b"keep-alive")
83
+ ]
84
+ assert r.headers.raw_items() == [
85
+ (b"Host", b"example.org"),
86
+ (b"Connection", b"keep-alive")
87
+ ]
88
+ """
89
+
90
+ def __init__ (self , full_items ):
91
+ self ._full_items = full_items
70
92
71
93
def __iter__ (self ):
72
- for _ , name , value in self .raw_items :
94
+ for _ , name , value in self ._full_items :
73
95
yield name , value
74
96
75
97
def __bool__ (self ):
76
- return bool (self .raw_items )
98
+ return bool (self ._full_items )
77
99
78
100
def __eq__ (self , other ):
79
101
return list (self ) == list (other )
80
102
103
+ def __len__ (self ):
104
+ return len (self ._full_items )
105
+
106
+ def raw_items (self ):
107
+ return [(raw_name , value ) for raw_name , _ , value in self ._full_items ]
108
+
81
109
82
110
def normalize_and_validate (headers , _parsed = False ):
83
111
new_headers = []
@@ -158,7 +186,7 @@ def get_comma_header(headers, name):
158
186
# "100-continue". Splitting on commas is harmless. Case insensitive.
159
187
#
160
188
out = []
161
- for _ , found_name , found_raw_value in headers .raw_items :
189
+ for _ , found_name , found_raw_value in headers ._full_items :
162
190
if found_name == name :
163
191
found_raw_value = found_raw_value .lower ()
164
192
for found_split_value in found_raw_value .split (b"," ):
@@ -171,7 +199,7 @@ def get_comma_header(headers, name):
171
199
def set_comma_header (headers , name , new_values ):
172
200
# The header name `name` is expected to be lower-case bytes.
173
201
new_headers = []
174
- for found_raw_name , found_name , found_raw_value in headers .raw_items :
202
+ for found_raw_name , found_name , found_raw_value in headers ._full_items :
175
203
if found_name != name :
176
204
new_headers .append ((found_raw_name , found_raw_value ))
177
205
for new_value in new_values :
0 commit comments