本文整理汇总了Python中wsgiref.headers.Headers.get方法的典型用法代码示例。如果您正苦于以下问题:Python Headers.get方法的具体用法?Python Headers.get怎么用?Python Headers.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wsgiref.headers.Headers
的用法示例。
在下文中一共展示了Headers.get方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testMappingInterface
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import get [as 别名]
def testMappingInterface(self):
test = [("x", "y")]
self.assertEqual(len(Headers([])), 0)
self.assertEqual(len(Headers(test[:])), 1)
self.assertEqual(Headers(test[:]).keys(), ["x"])
self.assertEqual(Headers(test[:]).values(), ["y"])
self.assertEqual(Headers(test[:]).items(), test)
self.assertIsNot(Headers(test).items(), test) # must be copy!
h = Headers([])
del h["foo"] # should not raise an error
h["Foo"] = "bar"
for m in h.has_key, h.__contains__, h.get, h.get_all, h.__getitem__:
self.assertTrue(m("foo"))
self.assertTrue(m("Foo"))
self.assertTrue(m("FOO"))
self.assertFalse(m("bar"))
self.assertEqual(h["foo"], "bar")
h["foo"] = "baz"
self.assertEqual(h["FOO"], "baz")
self.assertEqual(h.get_all("foo"), ["baz"])
self.assertEqual(h.get("foo", "whee"), "baz")
self.assertEqual(h.get("zoo", "whee"), "whee")
self.assertEqual(h.setdefault("foo", "whee"), "baz")
self.assertEqual(h.setdefault("zoo", "whee"), "whee")
self.assertEqual(h["foo"], "baz")
self.assertEqual(h["zoo"], "whee")
示例2: testMappingInterface
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import get [as 别名]
def testMappingInterface(self):
test = [('x','y')]
self.assertEqual(len(Headers([])),0)
self.assertEqual(len(Headers(test[:])),1)
self.assertEqual(Headers(test[:]).keys(), ['x'])
self.assertEqual(Headers(test[:]).values(), ['y'])
self.assertEqual(Headers(test[:]).items(), test)
self.assertFalse(Headers(test).items() is test) # must be copy!
h=Headers([])
del h['foo'] # should not raise an error
h['Foo'] = 'bar'
for m in h.__contains__, h.get, h.get_all, h.__getitem__:
self.assertTrue(m('foo'))
self.assertTrue(m('Foo'))
self.assertTrue(m('FOO'))
self.assertFalse(m('bar'))
self.assertEqual(h['foo'],'bar')
h['foo'] = 'baz'
self.assertEqual(h['FOO'],'baz')
self.assertEqual(h.get_all('foo'),['baz'])
self.assertEqual(h.get("foo","whee"), "baz")
self.assertEqual(h.get("zoo","whee"), "whee")
self.assertEqual(h.setdefault("foo","whee"), "baz")
self.assertEqual(h.setdefault("zoo","whee"), "whee")
self.assertEqual(h["foo"],"baz")
self.assertEqual(h["zoo"],"whee")
示例3: patched_start_response
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import get [as 别名]
def patched_start_response(status, headers, exc_info=None):
# if self._should_handle(headers)
wsgi_headers = Headers(headers)
# If we're debugging, or the response already has an expires
# header, just skip this.
if not self.debug and "Expires" not in wsgi_headers:
mime = wsgi_headers.get("Content-Type", "*").split(";")[0]
# If the mime type is explicitly called out, use the expire
# delay specified.
if mime in self.expire_seconds:
expire_time = self.make_expire_time_for(mime)
# If there's a catch-all wildcard delay, use that.
elif "*" in self.expire_seconds:
expire_time = self.make_expire_time_for("*")
# Otherwise, don't set the header.
else:
expire_time = None
if expire_time is not None:
log.debug("Adding expires header value: " + expire_time)
headers.append(("Expires", expire_time))
return start_response(status, headers, exc_info)
示例4: patched_start_response
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import get [as 别名]
def patched_start_response(status, headers, exc_info=None):
# if self._should_handle(headers)
wsgi_headers = Headers(headers)
# If we're debugging, or the response already has an expires
# header, just skip this.
log.debug('Skipping expired headers' if self.debug else 'Calculating expires headers')
if not self.debug and 'Expires' not in wsgi_headers:
mime = wsgi_headers.get('Content-Type', '*').split(';')[0]
log.debug('See mime type ' + mime)
# If the mime type is explicitly called out, use the expire
# delay specified.
if mime in self.expire_seconds:
log.debug('Matched mimetype exactly.')
expire_time = self.make_expire_time_for(mime)
# If there's a catch-all wildcard delay, use that.
elif '*' in self.expire_seconds:
log.debug('Matched mimetype with universal.')
expire_time = self.make_expire_time_for('*')
# Otherwise, don't set the header.
else:
log.debug('No mimetype match.')
expire_time = None
if expire_time is not None:
log.debug('Adding expires header value: ' + expire_time)
headers.append(('Expires', expire_time))
log.debug('-'*60)
return start_response(status, headers, exc_info)
示例5: __call__
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import get [as 别名]
def __call__(self, environ, start_response):
key_morsel = Cookie(environ.get("HTTP_COOKIE", "")).get(self.toggle_key)
# useful vars
query = query_str2dict(environ.get("QUERY_STRING"))
enable_by_cookie = key_morsel.value == self.enable_value if key_morsel else False
enable_by_query = query.get(self.toggle_key) == self.enable_value
# pop toggle_key from query dic to avoid case: '?_profile=on&_profile='
disable = query.pop(self.toggle_key, None) == "" # only can be disabled by query
enable = not disable and (enable_by_query or enable_by_cookie)
run_app, resp_body, saved_ss_args = self._intercept_call()
# processing cookies and queries
so = query.pop(self.SIMPLE_OUTPUT_TOGGLE_KEY, None)
if so is not None:
self.simple_output = so == "True"
cookie_to_set = None
if enable_by_query and not enable_by_cookie:
cookie_to_set = "%s=%s; Path=/; HttpOnly" % (self.toggle_key, self.enable_value)
elif disable:
cookie_to_set = "%s=; Path=/; Max-Age=1; HttpOnly" % self.toggle_key
if enable:
start = time.time()
profile = Profile()
profile.runcall(run_app, environ) # here we call the WSGI app
elapsed = time.time() - start
else:
profile = elapsed = None # for annoying IDE
run_app(environ)
status, headers = saved_ss_args[:2]
headers_dic = Headers(headers)
if cookie_to_set:
headers_dic.add_header("Set-Cookie", cookie_to_set)
# insert result into response
content_type = headers_dic.get("Content-Type", "")
if enable and status.startswith("200") and content_type.startswith("text/html"):
environ["QUERY_STRING"] = dict2query_str(query)
matched = _find_charset.match(content_type)
encoding = matched.group(1) if matched else "ascii"
rendered = self.render_result(profile, elapsed, environ).encode(encoding, "replace")
resp_body = [insert_into_body(rendered, b"".join(resp_body))]
headers_dic["Content-Length"] = str(len(resp_body[0]))
start_response(status, headers, saved_ss_args[2] if len(saved_ss_args) == 3 else None)
return resp_body
示例6: testBytes
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import get [as 别名]
def testBytes(self):
h = Headers([(b"Content-Type", b"text/plain; charset=utf-8")])
self.assertEqual("text/plain; charset=utf-8", h.get("Content-Type"))
h[b"Foo"] = bytes(b"bar")
self.assertEqual("bar", h.get("Foo"))
self.assertEqual("bar", h.get(b"Foo"))
h.setdefault(b"Bar", b"foo")
self.assertEqual("foo", h.get("Bar"))
self.assertEqual("foo", h.get(b"Bar"))
h.add_header(b"content-disposition", b"attachment", filename=b"bud.gif")
self.assertEqual('attachment; filename="bud.gif"', h.get("content-disposition"))
del h["content-disposition"]
self.assertTrue(b"content-disposition" not in h)
示例7: MultipartPart
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import get [as 别名]
class MultipartPart(object):
def __init__(self, buffer_size=2**16, memfile_limit=2**18, charset='latin1'):
self.headerlist = []
self.headers = None
self.file = False
self.size = 0
self._buf = tob('')
self.disposition, self.name, self.filename = None, None, None
self.content_type, self.charset = None, charset
self.memfile_limit = memfile_limit
self.buffer_size = buffer_size
def feed(self, line, nl=''):
if self.file:
return self.write_body(line, nl)
return self.write_header(line, nl)
def write_header(self, line, nl):
line = line.decode(self.charset or 'latin1')
if not nl:
raise MultipartError('Unexpected end of line in header.')
if not line.strip(): # blank line -> end of header segment
self.finish_header()
elif line[0] in ' \t' and self.headerlist:
name, value = self.headerlist.pop()
self.headerlist.append((name, value + line.strip()))
else:
if ':' not in line:
raise MultipartError("Syntax error in header: No colon.")
name, value = line.split(':', 1)
self.headerlist.append((name.strip(), value.strip()))
def write_body(self, line, nl):
if not line and not nl:
return # This does not even flush the buffer
self.size += len(line) + len(self._buf)
self.file.write(self._buf + line)
self._buf = nl
if self.content_length > 0 and self.size > self.content_length:
raise MultipartError('Size of body exceeds Content-Length header.')
if self.size > self.memfile_limit and isinstance(self.file, BytesIO):
# TODO: What about non-file uploads that exceed the memfile_limit?
self.file, old = TemporaryFile(mode='w+b'), self.file
old.seek(0)
copy_file(old, self.file, self.size, self.buffer_size)
def finish_header(self):
self.file = BytesIO()
self.headers = Headers(self.headerlist)
cdis = self.headers.get('Content-Disposition', '')
ctype = self.headers.get('Content-Type', '')
clen = self.headers.get('Content-Length', '-1')
if not cdis:
raise MultipartError('Content-Disposition header is missing.')
self.disposition, self.options = parse_options_header(cdis)
self.name = self.options.get('name')
self.filename = self.options.get('filename')
self.content_type, options = parse_options_header(ctype)
self.charset = options.get('charset') or self.charset
self.content_length = int(self.headers.get('Content-Length', '-1'))
def is_buffered(self):
''' Return true if the data is fully buffered in memory.'''
return isinstance(self.file, BytesIO)
@property
def value(self):
''' Data decoded with the specified charset '''
pos = self.file.tell()
self.file.seek(0)
val = self.file.read()
self.file.seek(pos)
return val.decode(self.charset)
def save_as(self, path):
fp = open(path, 'wb')
pos = self.file.tell()
try:
self.file.seek(0)
size = copy_file(self.file, fp)
finally:
self.file.seek(pos)
return size
示例8: MultipartPart
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import get [as 别名]
class MultipartPart(object):
def __init__(self, buffer_size=2 ** 16, memfile_limit=2 ** 18,
charset='latin1'):
self.headerlist = []
self.headers = None
self.file = False
self.size = 0
self._buf = tob('')
self.disposition, self.name, self.filename = None, None, None
self.content_type, self.charset = None, charset
self.memfile_limit = memfile_limit
self.buffer_size = buffer_size
def feed(self, line, nl=''):
if self.file:
return self.write_body(line, nl)
return self.write_header(line, nl)
def write_header(self, line, nl):
line = line.decode(self.charset or 'latin1')
if not nl:
raise MalformattedError('Unexpected end of line in header.')
if not line.strip(): # blank line -> end of header segment
self.finish_header()
elif line[0] in ' \t' and self.headerlist:
name, value = self.headerlist.pop()
self.headerlist.append((name, value + line.strip()))
else:
if ':' not in line:
raise MalformattedError("Syntax error in header: No colon.")
name, value = line.split(':', 1)
self.headerlist.append((name.strip(), value.strip()))
def write_body(self, line, nl):
if not line and not nl:
return # This does not even flush the buffer
if self.content_transfer_encoding and not nl:
raise MalformattedError('Line too long on transfer_encoded chunk.')
if self.content_transfer_encoding == 'quoted-printable':
if line.endswith(tob('=')):
nl = tob('')
line = quopri.decodestring(line)
elif self.content_transfer_encoding == 'base64':
line, nl = binascii.a2b_base64(line), tob('')
self.size += len(line) + len(self._buf)
self.file.write(self._buf + line)
self._buf = nl
if self.content_length > 0 and self.size > self.content_length:
raise MalformattedError('Size of body exceeds Content-Length header.')
if self.size > self.memfile_limit and isinstance(self.file, BytesIO):
self.file, old = TemporaryFile(mode='w+b'), self.file
old.seek(0)
copy_file(old, self.file, self.size, self.buffer_size)
def finish_header(self):
self.file = BytesIO()
self.headers = Headers(self.headerlist)
cdis = self.headers.get('Content-Disposition', '')
ctype = self.headers.get('Content-Type', '')
if not cdis:
raise MalformattedError('Content-Disposition header is missing.')
self.disposition, self.options = parse_options_header(cdis)
self.name = self.options.get('name')
self.filename = self.options.get('filename')
self.content_type, options = parse_options_header(ctype)
self.charset = options.get('charset') or self.charset
self.content_length = int(self.headers.get('Content-Length', '-1'))
self.content_transfer_encoding = \
self.headers.get('Content-Transfer-Encoding')
if self.content_transfer_encoding not in \
[None, 'base64', 'quoted-printable']:
raise MalformattedError('invalid Content-Transfer-Encoding')
def is_buffered(self):
''' Return true if the data is fully buffered in memory.'''
return isinstance(self.file, BytesIO)
def value(self, limit):
''' Data decoded with the specified charset '''
pos = self.file.tell()
try:
self.file.seek(0)
val = self.file.read(limit)
if self.file.read(1):
raise MemoryLimitError("Request too big. Increase mem_limit.")
finally:
self.file.seek(pos)
return val.decode(self.charset)
def save_as(self, path):
fp = open(path, 'wb')
pos = self.file.tell()
try:
self.file.seek(0)
size = copy_file(self.file, fp)
finally:
self.file.seek(pos)
return size
示例9: MultipartPart
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import get [as 别名]
class MultipartPart(object):
def __init__(self, buffer_size=2 ** 16, memfile_limit=2 ** 18, charset="latin1"):
self.headerlist = []
self.headers = None
self.file = False
self.size = 0
self._buf = tob("")
self.disposition, self.name, self.filename = None, None, None
self.content_type, self.charset = None, charset
self.memfile_limit = memfile_limit
self.buffer_size = buffer_size
def feed(self, line, nl=""):
if self.file:
return self.write_body(line, nl)
return self.write_header(line, nl)
def write_header(self, line, nl):
line = line.decode(self.charset or "latin1")
if not nl:
raise MultipartError("Unexpected end of line in header.")
if not line.strip(): # blank line -> end of header segment
self.finish_header()
elif line[0] in " \t" and self.headerlist:
name, value = self.headerlist.pop()
self.headerlist.append((name, value + line.strip()))
else:
if ":" not in line:
raise MultipartError("Syntax error in header: No colon.")
name, value = line.split(":", 1)
self.headerlist.append((name.strip(), value.strip()))
def write_body(self, line, nl):
if not line and not nl:
return # This does not even flush the buffer
self.size += len(line) + len(self._buf)
self.file.write(self._buf + line)
self._buf = nl
if self.content_length > 0 and self.size > self.content_length:
raise MultipartError("Size of body exceeds Content-Length header.")
if self.size > self.memfile_limit and isinstance(self.file, BytesIO):
# TODO: What about non-file uploads that exceed the memfile_limit?
self.file, old = TemporaryFile(mode="w+b"), self.file
old.seek(0)
copy_file(old, self.file, self.size, self.buffer_size)
def finish_header(self):
self.file = BytesIO()
self.headers = Headers(self.headerlist)
cdis = self.headers.get("Content-Disposition", "")
ctype = self.headers.get("Content-Type", "")
clen = self.headers.get("Content-Length", "-1")
if not cdis:
raise MultipartError("Content-Disposition header is missing.")
self.disposition, self.options = parse_options_header(cdis)
self.name = self.options.get("name")
self.filename = self.options.get("filename")
self.content_type, options = parse_options_header(ctype)
self.charset = options.get("charset") or self.charset
self.content_length = int(self.headers.get("Content-Length", "-1"))
def is_buffered(self):
""" Return true if the data is fully buffered in memory."""
return isinstance(self.file, BytesIO)
@property
def value(self):
""" Data decoded with the specified charset """
return self.raw.decode(self.charset)
@property
def raw(self):
""" Data without decoding """
pos = self.file.tell()
self.file.seek(0)
try:
val = self.file.read()
except IOError:
raise
finally:
self.file.seek(pos)
return val
def save_as(self, path):
fp = open(path, "wb")
pos = self.file.tell()
try:
self.file.seek(0)
size = copy_file(self.file, fp)
finally:
self.file.seek(pos)
return size