本文整理汇总了Python中hyper.common.headers.HTTPHeaderMap类的典型用法代码示例。如果您正苦于以下问题:Python HTTPHeaderMap类的具体用法?Python HTTPHeaderMap怎么用?Python HTTPHeaderMap使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HTTPHeaderMap类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_actual_get
def test_actual_get(self):
h = HTTPHeaderMap()
h['k1'] = 'v1, v2'
h['k2'] = 'v3'
h['k1'] = 'v4'
assert h.get('k1') == [b'v1', b'v2', b'v4']
示例2: test_keys
def test_keys(self):
h = HTTPHeaderMap()
h['k1'] = 'v1, v2'
h['k2'] = 'v3'
h['k1'] = 'v4'
assert len(list(h.keys())) == 4
assert list(h.keys()) == [b'k1', b'k1', b'k2', b'k1']
示例3: test_values
def test_values(self):
h = HTTPHeaderMap()
h['k1'] = 'v1, v2'
h['k2'] = 'v3'
h['k1'] = 'v4'
assert len(list(h.values())) == 4
assert list(h.values()) == [b'v1', b'v2', b'v3', b'v4']
示例4: test_raw_iteration
def test_raw_iteration(self):
items = [
(b'k1', b'v2'),
(b'k2', b'v2, v3, v4'),
(b'k2', b'v3'),
]
h = HTTPHeaderMap(items)
assert list(h.iter_raw()) == items
示例5: test_merge_header_map_dict
def test_merge_header_map_dict(self):
h = HTTPHeaderMap([(b'hi', b'there')])
d = {'cat': 'dog'}
h.merge(d)
assert list(h.items()) == [
(b'hi', b'there'),
(b'cat', b'dog'),
]
示例6: test_items
def test_items(self):
h = HTTPHeaderMap()
items = [
(b'k1', b'v2'),
(b'k2', b'v2'),
(b'k2', b'v3'),
]
for k, v in items:
h[k] = v
for i, pair in enumerate(h.items()):
assert items[i] == pair
示例7: test_merge_headermaps_preserves_raw
def test_merge_headermaps_preserves_raw(self):
h1 = HTTPHeaderMap([
(b'hi', b'there')
])
h2 = HTTPHeaderMap([
(b'Hi', b'there, sir, maam')
])
h1.merge(h2)
assert list(h1.iter_raw()) == [
(b'hi', b'there'),
(b'Hi', b'there, sir, maam'),
]
示例8: DummyResponse
class DummyResponse(object):
def __init__(self, headers):
self.headers = HTTPHeaderMap(headers.items())
def read(self):
ctype = self.headers.get('content-type')
if ctype is not None:
if 'json' in ctype[0].decode('utf-8'):
return b'{"data": "dummy"}'
return b'<html>dummy</html>'
def getheader(self, name):
return self.headers.get(name)
def getheaders(self):
return self.headers
示例9: __init__
def __init__(self,
ip,
stream_id,
host,
task,
send_cb,
close_cb,
header_encoder,
header_decoder,
receive_window_manager,
remote_window_size,
max_frame_size):
self.ip = ip
self.stream_id = stream_id
self.host = host
self.task = task
self.state = STATE_IDLE
# There are two flow control windows: one for data we're sending,
# one for data being sent to us.
self.receive_window_manager = receive_window_manager
self.remote_window_size = remote_window_size
self.max_frame_size = max_frame_size
# This is the callback handed to the stream by its parent connection.
# It is called when the stream wants to send data. It expects to
# receive a list of frames that will be automatically serialized.
self._send_cb = send_cb
# This is the callback to be called when the stream is closed.
self._close_cb = close_cb
# A reference to the header encoder and decoder objects belonging to
# the parent connection.
self._encoder = header_encoder
self._decoder = header_decoder
self.request_headers = HTTPHeaderMap()
# Convert the body to bytes if needed.
self.request_body = to_bytestring(self.task.body)
# request body not send blocked by send window
# the left body will send when send window opened.
self.request_body_left = len(self.request_body)
# data list before decode
self.response_header_datas = []
# Set to a key-value set of the response headers once their
# HEADERS..CONTINUATION frame sequence finishes.
self.response_headers = None
# Unconsumed response data chunks
self.response_body = []
self.response_body_len = 0
self.start_request()
示例10: test_replacing
def test_replacing(self):
h = HTTPHeaderMap([
(b'name', b'value'),
(b'name2', b'value2'),
(b'name2', b'value2'),
(b'name3', b'value3'),
])
h.replace('name2', '42')
h.replace('name4', 'other_value')
assert list(h.items()) == [
(b'name', b'value'),
(b'name2', b'42'),
(b'name3', b'value3'),
(b'name4', b'other_value'),
]
示例11: Stream
class Stream(object):
"""
A single HTTP/2 stream.
A stream is an independent, bi-directional sequence of HTTP headers and
data. Each stream is identified by a single integer. From a HTTP
perspective, a stream _approximately_ matches a single request-response
pair.
"""
def __init__(self,
connection,
ip,
stream_id,
host,
task,
send_cb,
close_cb,
header_encoder,
header_decoder,
receive_window_manager,
remote_window_size,
max_frame_size):
self.connection = connection
self.ip = ip
self.stream_id = stream_id
self.host = host
self.task = task
self.state = STATE_IDLE
# There are two flow control windows: one for data we're sending,
# one for data being sent to us.
self.receive_window_manager = receive_window_manager
self.remote_window_size = remote_window_size
self.max_frame_size = max_frame_size
# This is the callback handed to the stream by its parent connection.
# It is called when the stream wants to send data. It expects to
# receive a list of frames that will be automatically serialized.
self._send_cb = send_cb
# This is the callback to be called when the stream is closed.
self._close_cb = close_cb
# A reference to the header encoder and decoder objects belonging to
# the parent connection.
self._encoder = header_encoder
self._decoder = header_decoder
self.request_headers = HTTPHeaderMap()
# Convert the body to bytes if needed.
self.request_body = to_bytestring(self.task.body)
# request body not send blocked by send window
# the left body will send when send window opened.
self.request_body_left = len(self.request_body)
# data list before decode
self.response_header_datas = []
# Set to a key-value set of the response headers once their
# HEADERS..CONTINUATION frame sequence finishes.
self.response_headers = None
# Unconsumed response data chunks
self.response_body = []
self.response_body_len = 0
self.start_request()
def start_request(self):
"""
Open the stream. Does this by encoding and sending the headers: no more
calls to ``add_header`` are allowed after this method is called.
The `end` flag controls whether this will be the end of the stream, or
whether data will follow.
"""
# Strip any headers invalid in H2.
#headers = h2_safe_headers(self.request_headers)
self.add_header(":method", "POST")
self.add_header(":scheme", "https")
self.add_header(":authority", self.host)
self.add_header(":path", "/_gh/")
default_headers = (':method', ':scheme', ':authority', ':path')
for name, value in self.task.headers.items():
is_default = to_native_string(name) in default_headers
self.add_header(name, value, replace=is_default)
# Encode the headers.
encoded_headers = self._encoder.encode(self.request_headers)
# It's possible that there is a substantial amount of data here. The
# data needs to go into one HEADERS frame, followed by a number of
# CONTINUATION frames. For now, for ease of implementation, let's just
# assume that's never going to happen (16kB of headers is lots!).
# Additionally, since this is so unlikely, there's no point writing a
# test for this: it's just so simple.
#.........这里部分代码省略.........
示例12: __init__
def __init__(self, headers):
self.headers = HTTPHeaderMap(headers.items())
示例13: Stream
class Stream(object):
"""
A single HTTP/2 stream.
A stream is an independent, bi-directional sequence of HTTP headers and
data. Each stream is identified by a single integer. From a HTTP
perspective, a stream _approximately_ matches a single request-response
pair.
"""
def __init__(self,
logger,
config,
connection,
ip,
stream_id,
task,
send_cb,
close_cb,
encoder,
decoder,
receive_window_manager,
remote_window_size,
max_frame_size):
self.logger = logger
self.config = config
self.connection = connection
self.ip = ip
self.stream_id = stream_id
self.task = task
self.state = STATE_IDLE
self.get_head_time = None
# There are two flow control windows: one for data we're sending,
# one for data being sent to us.
self.receive_window_manager = receive_window_manager
self.remote_window_size = remote_window_size
self.max_frame_size = max_frame_size
# This is the callback handed to the stream by its parent connection.
# It is called when the stream wants to send data. It expects to
# receive a list of frames that will be automatically serialized.
self._send_cb = send_cb
# This is the callback to be called when the stream is closed.
self._close_cb = close_cb
# A reference to the header encoder and decoder objects belonging to
# the parent connection.
self._encoder = encoder
self._decoder = decoder
self.request_headers = HTTPHeaderMap()
# Convert the body to bytes if needed.
self.request_body = to_bytestring(self.task.body)
# request body not send blocked by send window
# the left body will send when send window opened.
self.request_body_left = len(self.request_body)
self.request_body_sended = False
# data list before decode
self.response_header_datas = []
# Set to a key-value set of the response headers once their
# HEADERS..CONTINUATION frame sequence finishes.
self.response_headers = None
# Unconsumed response data chunks
self.response_body = []
self.response_body_len = 0
def start_request(self):
"""
Open the stream. Does this by encoding and sending the headers: no more
calls to ``add_header`` are allowed after this method is called.
The `end` flag controls whether this will be the end of the stream, or
whether data will follow.
"""
# Strip any headers invalid in H2.
#headers = h2_safe_headers(self.request_headers)
host = self.connection.get_host(self.task.host)
self.add_header(":method", self.task.method)
self.add_header(":scheme", "https")
self.add_header(":authority", host)
self.add_header(":path", self.task.path)
default_headers = (':method', ':scheme', ':authority', ':path')
#headers = h2_safe_headers(self.task.headers)
for name, value in self.task.headers.items():
is_default = to_native_string(name) in default_headers
self.add_header(name, value, replace=is_default)
# Encode the headers.
encoded_headers = self._encoder(self.request_headers)
# It's possible that there is a substantial amount of data here. The
#.........这里部分代码省略.........
示例14: receive_frame
def receive_frame(self, frame):
"""
Handle a frame received on this stream.
called by connection.
"""
# self.logger.debug("stream %d recved frame %r", self.stream_id, frame)
if frame.type == WindowUpdateFrame.type:
self.remote_window_size += frame.window_increment
self.send_left_body()
elif frame.type == HeadersFrame.type:
# Begin the header block for the response headers.
#self.response_header_datas = [frame.data]
self.response_header_datas.append(frame.data)
elif frame.type == PushPromiseFrame.type:
self.logger.error("%s receive PushPromiseFrame:%d", self.ip, frame.stream_id)
elif frame.type == ContinuationFrame.type:
# Continue a header block begun with either HEADERS or PUSH_PROMISE.
self.response_header_datas.append(frame.data)
elif frame.type == DataFrame.type:
# Append the data to the buffer.
if not self.task.finished:
self.task.put_data(frame.data)
if 'END_STREAM' not in frame.flags:
# Increase the window size. Only do this if the data frame contains
# actual data.
# don't do it if stream is closed.
size = frame.flow_controlled_length
increment = self.receive_window_manager._handle_frame(size)
#if increment:
# self.logger.debug("stream:%d frame size:%d increase win:%d", self.stream_id, size, increment)
#content_len = int(self.request_headers.get("Content-Length")[0])
#self.logger.debug("%s get:%d s:%d", self.ip, self.response_body_len, size)
if increment and not self._remote_closed:
w = WindowUpdateFrame(self.stream_id)
w.window_increment = increment
self._send_cb(w)
elif frame.type == BlockedFrame.type:
# If we've been blocked we may want to fixup the window.
increment = self.receive_window_manager._blocked()
if increment:
w = WindowUpdateFrame(self.stream_id)
w.window_increment = increment
self._send_cb(w)
elif frame.type == RstStreamFrame.type:
# Rest Frame send from server is not define in RFC
inactive_time = time.time() - self.connection.last_active_time
self.logger.debug("%s Stream %d Rest by server, inactive:%d. error code:%d",
self.ip, self.stream_id, inactive_time, frame.error_code)
self.connection.close("RESET")
elif frame.type in FRAMES:
# This frame isn't valid at this point.
#raise ValueError("Unexpected frame %s." % frame)
self.logger.error("%s Unexpected frame %s.", self.ip, frame)
else: # pragma: no cover
# Unknown frames belong to extensions. Just drop it on the
# floor, but log so that users know that something happened.
self.logger.error("%s Received unknown frame, type %d", self.ip, frame.type)
pass
if 'END_HEADERS' in frame.flags:
if self.response_headers is not None:
raise ProtocolError("Too many header blocks.")
# Begin by decoding the header block. If this fails, we need to
# tear down the entire connection.
if len(self.response_header_datas) == 1:
header_data = self.response_header_datas[0]
else:
header_data = b''.join(self.response_header_datas)
try:
headers = self._decoder.decode(header_data)
except Exception as e:
self.logger.exception("decode h2 header %s fail:%r", header_data, e)
raise e
self.response_headers = HTTPHeaderMap(headers)
# We've handled the headers, zero them out.
self.response_header_datas = None
self.get_head_time = time.time()
length = self.response_headers.get("Content-Length", None)
if isinstance(length, list):
length = int(length[0])
if not self.task.finished:
self.task.content_length = length
self.task.set_state("h2_get_head")
self.send_response()
if 'END_STREAM' in frame.flags:
#self.logger.debug("%s Closing remote side of stream:%d", self.ip, self.stream_id)
time_now = time.time()
time_cost = time_now - self.get_head_time
if time_cost > 0 and \
isinstance(self.task.content_length, int) and \
#.........这里部分代码省略.........
示例15: test_empty_get
def test_empty_get(self):
h = HTTPHeaderMap()
assert h.get('nonexistent', 'hi there') == 'hi there'