本文整理汇总了Python中multidict.CIMultiDict.items方法的典型用法代码示例。如果您正苦于以下问题:Python CIMultiDict.items方法的具体用法?Python CIMultiDict.items怎么用?Python CIMultiDict.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类multidict.CIMultiDict
的用法示例。
在下文中一共展示了CIMultiDict.items方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: HttpTunnel
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
class HttpTunnel(RequestBase):
first_line = None
data = None
decompress = False
method = 'CONNECT'
def __init__(self, client, req):
self.client = client
self.key = req
self.headers = CIMultiDict(client.DEFAULT_TUNNEL_HEADERS)
def __repr__(self):
return 'Tunnel %s' % self.url
__str__ = __repr__
def encode(self):
self.headers['host'] = self.key.netloc
self.first_line = 'CONNECT http://%s:%s HTTP/1.1' % self.key.address
buffer = [self.first_line.encode('ascii'), b'\r\n']
buffer.extend((('%s: %s\r\n' % (name, value)).encode(CHARSET)
for name, value in self.headers.items()))
buffer.append(b'\r\n')
return b''.join(buffer)
def has_header(self, header_name):
return header_name in self.headers
def get_header(self, header_name, default=None):
return self.headers.get(header_name, default)
def remove_header(self, header_name):
self.headers.pop(header_name, None)
示例2: start
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
async def start(self, connection, read_until_eof=False):
# vk.com return url like this: http://REDIRECT_URI#access_token=...
# but aiohttp by default removes all parameters after '#'
await super().start(connection, read_until_eof)
headers = CIMultiDict(self.headers)
location = headers.get(hdrs.LOCATION, None)
if location:
headers[hdrs.LOCATION] = location.replace('#', '?')
self.headers = CIMultiDictProxy(headers)
self.raw_headers = tuple(headers.items())
return self
示例3: _prepare_headers
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
def _prepare_headers(self, headers):
""" Add default headers and transform it to CIMultiDict
"""
# Convert headers to MultiDict
result = CIMultiDict(self._default_headers)
if headers:
if not isinstance(headers, (MultiDictProxy, MultiDict)):
headers = CIMultiDict(headers)
added_names = set()
for key, value in headers.items():
if key in added_names:
result.add(key, value)
else:
result[key] = value
added_names.add(key)
return result
示例4: maker
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
def maker(method, path, headers=None, *,
version=HttpVersion(1, 1), closing=False,
sslcontext=None,
secure_proxy_ssl_header=None):
if version < HttpVersion(1, 1): # noqa
closing = True
if headers is None:
headers = {}
headers = CIMultiDict(headers)
app = mock.Mock()
app._debug = False
app.on_response_prepare = Signal(app)
if "HOST" not in headers:
headers["HOST"] = "test.local" # noqa
message = RawRequestMessage(method, path, version, headers,
[(k.encode('utf-8'), v.encode('utf-8'))
for k, v in headers.items()],
closing, False)
payload = mock.Mock()
transport = mock.Mock()
def get_extra_info(key): # noqa
if key == 'sslcontext':
return sslcontext
else:
return None
transport.get_extra_info.side_effect = get_extra_info
writer = mock.Mock()
reader = mock.Mock()
req = Request(app, message, payload,
transport, reader, writer,
secure_proxy_ssl_header=secure_proxy_ssl_header)
return req
示例5: __init__
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
#.........这里部分代码省略.........
if not url.host:
raise ValueError('Host could not be detected.')
# basic auth info
username, password = url.user, url.password
if username:
self.auth = helpers.BasicAuth(username, password or '')
# Record entire netloc for usage in host header
scheme = url.scheme
self.ssl = scheme in ('https', 'wss')
def update_version(self, version):
"""Convert request version to two elements tuple.
parser HTTP version '1.1' => (1, 1)
"""
if isinstance(version, str):
v = [l.strip() for l in version.split('.', 1)]
try:
version = int(v[0]), int(v[1])
except ValueError:
raise ValueError(
'Can not parse http version number: {}'
.format(version)) from None
self.version = version
def update_headers(self, headers):
"""Update request headers."""
self.headers = CIMultiDict()
if headers:
if isinstance(headers, dict):
headers = headers.items()
elif isinstance(headers, (MultiDictProxy, MultiDict)):
headers = headers.items()
for key, value in headers:
self.headers.add(key, value)
def update_auto_headers(self, skip_auto_headers):
self.skip_auto_headers = skip_auto_headers
used_headers = set(self.headers) | skip_auto_headers
for hdr, val in self.DEFAULT_HEADERS.items():
if hdr not in used_headers:
self.headers.add(hdr, val)
# add host
if hdrs.HOST not in used_headers:
netloc = self.url.host
if not self.url.is_default_port():
netloc += ':' + str(self.url.port)
self.headers[hdrs.HOST] = netloc
if hdrs.USER_AGENT not in used_headers:
self.headers[hdrs.USER_AGENT] = self.SERVER_SOFTWARE
def update_cookies(self, cookies):
"""Update request cookies header."""
if not cookies:
return
c = http.cookies.SimpleCookie()
if hdrs.COOKIE in self.headers:
c.load(self.headers.get(hdrs.COOKIE, ''))
示例6: make_mocked_request
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
def make_mocked_request(method, path, headers=None, *,
version=HttpVersion(1, 1), closing=False,
app=None,
writer=sentinel,
payload_writer=sentinel,
protocol=sentinel,
transport=sentinel,
payload=sentinel,
sslcontext=None,
secure_proxy_ssl_header=None,
client_max_size=1024**2,
loop=...):
"""Creates mocked web.Request testing purposes.
Useful in unit tests, when spinning full web server is overkill or
specific conditions and errors are hard to trigger.
"""
task = mock.Mock()
if loop is ...:
loop = mock.Mock()
loop.create_future.return_value = ()
if version < HttpVersion(1, 1):
closing = True
if headers:
headers = CIMultiDict(headers)
raw_hdrs = tuple(
(k.encode('utf-8'), v.encode('utf-8')) for k, v in headers.items())
else:
headers = CIMultiDict()
raw_hdrs = ()
chunked = 'chunked' in headers.get(hdrs.TRANSFER_ENCODING, '').lower()
message = RawRequestMessage(
method, path, version, headers,
raw_hdrs, closing, False, False, chunked, URL(path))
if app is None:
app = _create_app_mock()
if protocol is sentinel:
protocol = mock.Mock()
if transport is sentinel:
transport = _create_transport(sslcontext)
if writer is sentinel:
writer = mock.Mock()
writer.transport = transport
if payload_writer is sentinel:
payload_writer = mock.Mock()
payload_writer.write_eof.side_effect = noop
payload_writer.drain.side_effect = noop
protocol.transport = transport
protocol.writer = writer
if payload is sentinel:
payload = mock.Mock()
time_service = mock.Mock()
time_service.time.return_value = 12345
time_service.strtime.return_value = "Tue, 15 Nov 1994 08:12:31 GMT"
@contextmanager
def timeout(*args, **kw):
yield
time_service.timeout = mock.Mock()
time_service.timeout.side_effect = timeout
req = Request(message, payload,
protocol, payload_writer, time_service, task, loop,
secure_proxy_ssl_header=secure_proxy_ssl_header,
client_max_size=client_max_size)
match_info = UrlMappingMatchInfo({}, mock.Mock())
match_info.add_app(app)
req._match_info = match_info
return req
示例7: __init__
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
#.........这里部分代码省略.........
scheme = url_parsed.scheme
self.ssl = scheme in ("https", "wss")
# set port number if it isn't already set
if not port:
if self.ssl:
port = HTTPS_PORT
else:
port = HTTP_PORT
self.host, self.port, self.scheme = host, port, scheme
def update_version(self, version):
"""Convert request version to two elements tuple.
parser HTTP version '1.1' => (1, 1)
"""
if isinstance(version, str):
v = [l.strip() for l in version.split(".", 1)]
try:
version = int(v[0]), int(v[1])
except ValueError:
raise ValueError("Can not parse http version number: {}".format(version)) from None
self.version = version
def update_path(self, params):
"""Build path."""
# extract path
scheme, netloc, path, query, fragment = urllib.parse.urlsplit(self.url)
if not path:
path = "/"
if isinstance(params, collections.Mapping):
params = list(params.items())
if params:
if not isinstance(params, str):
params = urllib.parse.urlencode(params)
if query:
query = "%s&%s" % (query, params)
else:
query = params
self.path = urllib.parse.urlunsplit(("", "", helpers.requote_uri(path), query, fragment))
self.url = urllib.parse.urlunsplit((scheme, netloc, self.path, "", ""))
def update_headers(self, headers):
"""Update request headers."""
self.headers = CIMultiDict()
if headers:
if isinstance(headers, dict):
headers = headers.items()
elif isinstance(headers, (MultiDictProxy, MultiDict)):
headers = headers.items()
for key, value in headers:
self.headers.add(key, value)
def update_auto_headers(self, skip_auto_headers):
self.skip_auto_headers = skip_auto_headers
used_headers = set(self.headers) | skip_auto_headers
for hdr, val in self.DEFAULT_HEADERS.items():
if hdr not in used_headers:
self.headers.add(hdr, val)
示例8: HttpMessage
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
#.........这里部分代码省略.........
if self.version < HttpVersion10:
# keep alive not supported at all
return False
if self.version == HttpVersion10:
if self.headers.get(hdrs.CONNECTION) == 'keep-alive':
return True
else: # no headers means we close for Http 1.0
return False
else:
return not self.closing
else:
return self.keepalive
def is_headers_sent(self):
return self.headers_sent
def add_header(self, name, value):
"""Analyze headers. Calculate content length,
removes hop headers, etc."""
assert not self.headers_sent, 'headers have been sent already'
assert isinstance(name, str), \
'Header name should be a string, got {!r}'.format(name)
assert set(name).issubset(ASCIISET), \
'Header name should contain ASCII chars, got {!r}'.format(name)
assert isinstance(value, str), \
'Header {!r} should have string value, got {!r}'.format(
name, value)
name = istr(name)
value = value.strip()
if name == hdrs.CONTENT_LENGTH:
self.length = int(value)
if name == hdrs.TRANSFER_ENCODING:
self.has_chunked_hdr = value.lower() == 'chunked'
if name == hdrs.CONNECTION:
val = value.lower()
# handle websocket
if 'upgrade' in val:
self.upgrade = True
# connection keep-alive
elif 'close' in val:
self.keepalive = False
elif 'keep-alive' in val:
self.keepalive = True
elif name == hdrs.UPGRADE:
if 'websocket' in value.lower():
self.websocket = True
self.headers[name] = value
elif name not in self.HOP_HEADERS:
# ignore hop-by-hop headers
self.headers.add(name, value)
def add_headers(self, *headers):
"""Adds headers to a HTTP message."""
for name, value in headers:
self.add_header(name, value)
def send_headers(self, _sep=': ', _end='\r\n'):
"""Writes headers to a stream. Constructs payload writer."""
# Chunked response is only for HTTP/1.1 clients or newer
# and there is no Content-Length header is set.
# Do not use chunked responses when the response is guaranteed to
# not have a response body (304, 204).
assert not self.headers_sent, 'headers have been sent already'
self.headers_sent = True
if not self.chunked and self.autochunked():
self.enable_chunking()
if self.chunked:
self.headers[hdrs.TRANSFER_ENCODING] = 'chunked'
self._add_default_headers()
# status + headers
headers = self.status_line + ''.join(
[k + _sep + v + _end for k, v in self.headers.items()])
headers = headers.encode('utf-8') + b'\r\n'
self.buffer_data(headers)
def _add_default_headers(self):
# set the connection header
connection = None
if self.upgrade:
connection = 'Upgrade'
elif not self.closing if self.keepalive is None else self.keepalive:
if self.version == HttpVersion10:
connection = 'keep-alive'
else:
if self.version == HttpVersion11:
connection = 'close'
if connection is not None:
self.headers[hdrs.CONNECTION] = connection
示例9: make_mocked_request
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
def make_mocked_request(method, path, headers=None, *,
match_info=sentinel,
version=HttpVersion(1, 1), closing=False,
app=None,
writer=sentinel,
protocol=sentinel,
transport=sentinel,
payload=sentinel,
sslcontext=None,
client_max_size=1024**2,
loop=...):
"""Creates mocked web.Request testing purposes.
Useful in unit tests, when spinning full web server is overkill or
specific conditions and errors are hard to trigger.
"""
task = mock.Mock()
if loop is ...:
loop = mock.Mock()
loop.create_future.return_value = ()
if version < HttpVersion(1, 1):
closing = True
if headers:
headers = CIMultiDict(headers)
raw_hdrs = tuple(
(k.encode('utf-8'), v.encode('utf-8')) for k, v in headers.items())
else:
headers = CIMultiDict()
raw_hdrs = ()
chunked = 'chunked' in headers.get(hdrs.TRANSFER_ENCODING, '').lower()
message = RawRequestMessage(
method, path, version, headers,
raw_hdrs, closing, False, False, chunked, URL(path))
if app is None:
app = _create_app_mock()
if protocol is sentinel:
protocol = mock.Mock()
if transport is sentinel:
transport = _create_transport(sslcontext)
if writer is sentinel:
writer = mock.Mock()
writer.write_headers = make_mocked_coro(None)
writer.write = make_mocked_coro(None)
writer.write_eof = make_mocked_coro(None)
writer.drain = make_mocked_coro(None)
writer.transport = transport
protocol.transport = transport
protocol.writer = writer
if payload is sentinel:
payload = mock.Mock()
req = Request(message, payload,
protocol, writer, task, loop,
client_max_size=client_max_size)
match_info = UrlMappingMatchInfo(
{} if match_info is sentinel else match_info, mock.Mock())
match_info.add_app(app)
req._match_info = match_info
return req
示例10: __init__
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
#.........这里部分代码省略.........
self._method = method
def __str__(self):
if self._payload:
self._raw_payload = self._payload.encode()
elif not self._raw_payload:
self._raw_payload = b''
msg = self._make_headers()
return msg + self.payload
def encode(self, *args, **kwargs):
if self._payload:
self._raw_payload = self._payload.encode(*args, **kwargs)
elif not self._raw_payload:
self._raw_payload = b''
msg = self._make_headers()
return msg.encode(*args, **kwargs) + self._raw_payload
def _make_headers(self):
if hasattr(self, '_from_details'):
self.headers['From'] = str(self.from_details)
if hasattr(self, '_to_details'):
self.headers['To'] = str(self.to_details)
if hasattr(self, '_contact_details'):
self.headers['Contact'] = str(self.contact_details)
if hasattr(self, '_cseq'):
self.headers['CSeq'] = '%s %s' % (self.cseq, self.method)
elif hasattr(self, '_method'):
self.headers['CSeq'] = '%s %s' % (self.cseq, self.method)
self.headers['Content-Length'] = str(len(self._raw_payload))
if 'Max-Forwards' not in self.headers:
self.headers['Max-Forwards'] = '70'
if 'Call-ID' not in self.headers:
self.headers['Call-ID'] = uuid.uuid4()
return self._format_headers()
def _format_headers(self):
msg = []
for k, v in sorted(self.headers.items()):
if k == 'Via':
if isinstance(v, (list, tuple)):
msg = ['%s: %s' % (k, i) for i in v] + msg
else:
msg.insert(0, '%s: %s' % (k, v))
else:
if isinstance(v, (list, tuple)):
msg.extend(['%s: %s' % (k, i) for i in v])
else:
msg.append('%s: %s' % (k, v))
msg.append(utils.EOL)
return utils.EOL.join(msg)
def parsed_xml(self):
if 'Content-Type' not in self.headers:
return None
if not self.headers['Content-Type'].endswith('+xml'):
return None
return PyQuery(self.payload).remove_namespaces()
@classmethod
def from_raw_headers(cls, raw_headers):
headers = CIMultiDict()
decoded_headers = raw_headers.decode().split(utils.EOL)
for line in decoded_headers[1:]:
k, v = line.split(': ', 1)
if k in headers:
o = headers.setdefault(k, [])
if not isinstance(o, list):
o = [o]
o.append(v)
headers[k] = o
else:
headers[k] = v
m = FIRST_LINE_PATTERN['response']['regex'].match(decoded_headers[0])
if m:
d = m.groupdict()
return Response(status_code=int(d['status_code']),
status_message=d['status_message'],
headers=headers,
first_line=decoded_headers[0])
else:
m = FIRST_LINE_PATTERN['request']['regex'].match(decoded_headers[0])
if m:
d = m.groupdict()
cseq, _ = headers['CSeq'].split()
return Request(method=d['method'],
headers=headers,
cseq=int(cseq),
first_line=decoded_headers[0])
else:
LOG.debug(decoded_headers)
raise ValueError('Not a SIP message')
示例11: __init__
# 需要导入模块: from multidict import CIMultiDict [as 别名]
# 或者: from multidict.CIMultiDict import items [as 别名]
class Message:
def __init__(self,
# from_uri,
# to_uri,
content_type=None,
headers=None,
payload=None):
# self.from_uri = from_uri
# self.to_uri = to_uri
if headers:
self.headers = headers
else:
self.headers = CIMultiDict()
for direction in ('From', 'To', 'Contact'): # parse From, To, and Contact headers
direction_attribute = '%s_details' % direction.lower()
if direction in self.headers:
if not hasattr(self, direction_attribute):
setattr(self,
direction_attribute,
Contact.from_header(self.headers[direction]))
elif hasattr(self, direction_attribute):
contact = getattr(self, direction_attribute)
self.headers[direction] = str(contact)
elif direction != 'Contact':
raise(ValueError('You must have a "%s" header or details.' % direction))
if content_type:
self.headers['Content-Type'] = content_type
self.payload = payload
# Build the message
if 'Via' not in self.headers:
self.headers['Via'] = 'SIP/2.0/%(protocol)s '+'%s:%s;branch=%s' % (self.contact_details['uri']['host'],
self.contact_details['uri']['port'],
utils.gen_branch(10))
if 'Max-Forwards' not in self.headers:
self.headers['Max-Forwards'] = '70'
if 'Call-ID' not in self.headers:
self.headers['Call-ID'] = uuid.uuid4()
if 'User-Agent' not in self.headers:
self.headers['User-Agent'] = 'Python/{0[0]}.{0[1]}.{0[2]} aiosip/{1}'.format(
sys.version_info, aiosip.__version__)
if 'Content-Length' not in self.headers:
payload_len = len(self.payload.encode()) if self.payload else 0
self.headers['Content-Length'] = payload_len
@property
def cseq(self):
if not hasattr(self, '_cseq'):
self._cseq = int(self.headers['CSeq'].split(' ')[0])
return self._cseq
@property
def method(self):
if not hasattr(self, '_method'):
self._method = self.headers['CSeq'].split(' ')[1]
return self._method
def __str__(self):
msg = []
for k, v in sorted(self.headers.items()):
if isinstance(v, (list, tuple)):
msg.extend(['%s: %s' % (k, i) for i in v])
else:
msg.append('%s: %s' % (k, v))
if self.payload:
msg.append('%s%s' % (utils.EOL, self.payload))
else:
msg.append(utils.EOL)
return utils.EOL.join(msg)
def parsed_xml(self):
if 'Content-Type' not in self.headers:
return None
if not self.headers['Content-Type'].endswith('+xml'):
return None
return PyQuery(self.payload).remove_namespaces()
@classmethod
def from_raw_message(cls, raw_message):
lines = raw_message.split(utils.EOL)
first_line = lines.pop(0)
headers = CIMultiDict()
payload = ''
reading_headers = True
for line in lines:
if reading_headers:
if ': ' in line:
k, v = line.split(': ', 1)
if k in headers:
o = headers.setdefault(k, [])
if not isinstance(o, list):
o = [o]
o.append(v)
headers[k] = o
else:
headers[k] = v
else: # Finish to parse headers
reading_headers = False
#.........这里部分代码省略.........