本文整理汇总了Python中wsgiref.headers.Headers.items方法的典型用法代码示例。如果您正苦于以下问题:Python Headers.items方法的具体用法?Python Headers.items怎么用?Python Headers.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wsgiref.headers.Headers
的用法示例。
在下文中一共展示了Headers.items方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: thread_app
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
def thread_app(env, resp):
path = env['PATH_INFO']
# utils.log('thread_app', path)
m = thread_re.match(path)
board, datkey = m.group(1), m.group(2)
key = keylib.get_filekey(datkey)
data = cache.Cache(key)
data.load()
if check_get_cache(env):
if not data.exists() or len(data) == 0:
# when first access, load data from network
data.search()
elif _count_is_update(key):
# update thread
# limit `data.search` calling. it's slow!
threading.Thread(target=data.search, daemon=True).start()
if not data.exists():
resp('404 Not Found', [('Content-Type', 'text/plain; charset=Shift_JIS')])
return [b'404 Not Found']
thread = dat.make_dat(data, env, board)
headers = Headers([('Content-Type', 'text/plain; charset=Shift_JIS')])
last_m = eutils.formatdate(data.stamp)
headers['Last-Modified'] = last_m
resp("200 OK", headers.items())
return (c.encode('cp932', 'replace') for c in thread)
示例2: handle_application_error
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
def handle_application_error(self, environ, start_response):
status = "500 Internal Server Error"
headers = Headers([])
# Package the exception info as into a special header and
# send it to the client
type, exc, tb = sys.exc_info()
tbfile = StringIO()
traceback.print_exc(file=tbfile)
headers['Content-Type'] = 'text/plain; charset=utf-8'
LOG.debug("Packing traceback context into debug header: %s",
self.debug_header)
debug_header = self.pack_header(Traceback(tb))
LOG.debug("Debug header (%d bytes): %s",
len(debug_header), debug_header)
headers[self.debug_header] = debug_header
app_uri = application_uri(environ)
headers["Location"] = app_uri[:-1] + self.debug_uri
start_response(status, headers.items())
return [tbfile.getvalue().encode('utf-8')]
示例3: board_app
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
def board_app(env, resp):
path = env['PATH_INFO']
m = board_re.match(path)
board = m.group(1)
message = gateway.search_message(env.get('HTTP_ACCEPT_LANGUAGE', 'ja'))
headers = Headers([('Content-Type', 'text/html; charset=Shift_JIS')])
resp("200 OK", headers.items())
board = utils.sanitize(utils.get_board(path))
if board:
fmt = '{logo} - {board} - {desc}'
else:
fmt = '{logo} - {desc}'
text = fmt.format(logo=message['logo'], desc=message['description'], board=board)
html = '''
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=Shift_JIS">
<title>{text}</title>
<meta name="description" content="{text}">
</head><body>
<h1>{text}</h1>
</body></html>
'''.format(text=text)
return [html.encode('cp932', 'replace')]
示例4: newapp
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
def newapp(environ, start_response):
body = app(environ, capture)
status = resp['status']
headers = Headers(resp['headers'])
already = 'Content-Encoding' in headers
accepted = 'gzip' in environ.get('HTTP_ACCEPT_ENCODING', '')
if not accepted or already:
# no compress
start_response(status, list(headers.items()))
return body
content = gzip.compress(b''.join(body))
if hasattr(body, 'close'):
body.close()
headers['Content-Encoding'] = 'gzip'
start_response(status, list(headers.items()))
return [content]
示例5: get_alternatives
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
def get_alternatives(base_headers, files):
# Sort by size so that the smallest compressed alternative matches first
alternatives = []
files_by_size = sorted(files.items(), key=lambda i: i[1].stat.st_size)
for encoding, file_entry in files_by_size:
headers = Headers(base_headers.items())
headers['Content-Length'] = str(file_entry.stat.st_size)
if encoding:
headers['Content-Encoding'] = encoding
encoding_re = re.compile(r'\b%s\b' % encoding)
else:
encoding_re = re.compile('')
alternatives.append((encoding_re, file_entry.path, headers.items()))
return alternatives
示例6: get_static_file
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
def get_static_file(self, path, url, stat_cache=None):
# Optimization: bail early if file does not exist
if stat_cache is None and not os.path.exists(path):
raise MissingFileError(path)
headers = Headers([])
self.add_mime_headers(headers, path, url)
self.add_cache_headers(headers, path, url)
if self.allow_all_origins:
headers['Access-Control-Allow-Origin'] = '*'
if self.add_headers_function:
self.add_headers_function(headers, path, url)
return StaticFile(
path, headers.items(),
stat_cache=stat_cache,
encodings={
'gzip': path + '.gz', 'br': path + '.br'})
示例7: Response
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
class Response(threading.local):
""" Represents a single response using thread-local namespace. """
def bind(self):
""" Clears old data and creates a brand new Response object """
self._COOKIES = None
self.status = 200
self.header_list = []
self.header = HeaderWrapper(self.header_list)
self.content_type = 'text/html'
self.error = None
self.charset = 'utf8'
def wsgiheaders(self):
''' Returns a wsgi conform list of header/value pairs '''
for c in self.COOKIES.itervalues():
self.header.add_header('Set-Cookie', c.OutputString())
return [(h.title(), str(v)) for h, v in self.header.items()]
@property
def COOKIES(self):
if not self._COOKIES:
self._COOKIES = SimpleCookie()
return self._COOKIES
def set_cookie(self, key, value, **kargs):
"""
Sets a Cookie. Optional settings:
expires, path, comment, domain, max-age, secure, version, httponly
"""
self.COOKIES[key] = value
for k, v in kargs.iteritems():
self.COOKIES[key][k] = v
def get_content_type(self):
""" Get the current 'Content-Type' header. """
return self.header['Content-Type']
def set_content_type(self, value):
if 'charset=' in value:
self.charset = value.split('charset=')[-1].split(';')[0].strip()
self.header['Content-Type'] = value
content_type = property(get_content_type, set_content_type, None,
get_content_type.__doc__)
示例8: board_app
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
def board_app(env, resp):
path = env['PATH_INFO']
m = board_re.match(path)
board = m.group(1)
message = gateway.search_message(env.get('HTTP_ACCEPT_LANGUAGE', 'ja'))
headers = Headers([('Content-Type', 'text/html; charset=Shift_JIS')])
resp("200 OK", headers.items())
html = [
'<!DOCTYPE html>',
'<html><head>',
'<meta http-equiv="content-type" content="text/html; charset=Shift_JIS">',
'<title>%s - %s</title>' % (message['logo'], message['description']),
'<meta name="description" content="%s - %s">' % (message['logo'], message['description']),
'</head><body>',
'<h1>%s - %s</h1>' % (message['logo'], message['description']),
'</body></html>',
]
return ((c + '\n').encode('sjis', 'ignore') for c in html)
示例9: BeanServer
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
class BeanServer(object):
"A really, really simple application server."
default_headers = [('Content-Type', 'text/html')]
def __init__(self, ledger, opts):
self.ledger = ledger
self.data = []
self.load()
# Map of session to dict.
self.cookiejar = {}
# Prototype for context object.
ctx = self.ctx = Context()
self.opts = ctx.opts = opts
ctx.debug = opts.debug
def setHeader(self, name, value):
self.headers[name] = value
def write(self, data):
assert isinstance(data, str), data
self.data.append(data)
def load(self):
"Load the application pages."
import app
reload(app)
self.mapper = app.mapper
def __call__(self, environ, start_response):
if self.ctx.debug:
self.load()
self.environ = environ
self.response = start_response
del self.data[:]
self.headers = Headers(self.default_headers)
ctx = copy(self.ctx) # shallow
ctx.ledger = self.ledger
path = environ['PATH_INFO']
ishtml = '.' not in basename(path) or path.endswith('.html')
if ishtml:
# Load cookie (session is only in memory).
cookie = Cookie.SimpleCookie(environ.get('HTTP_COOKIE', ''))
has_cookie = (bool(cookie) and
'session' in cookie and
cookie["session"].value in self.cookiejar)
if has_cookie:
session_id = cookie["session"].value
session = self.cookiejar[session_id]
else:
session_id = '%x' % randint(0, 16**16)
cookie["session"] = session_id
session = self.cookiejar[session_id] = {}
ctx.session = session
try:
# Linear search in the regexp to match the request path.
page, vardict = self.mapper.match(path)
if page is None:
raise HttpNotFound(path)
else:
# Update the context object with components of the request and
# with the query parameters.
ctx.environ = environ
form = cgi.parse(environ=environ)
## FIXME: make this wsgi compatible.
## conlen = int(self.environ['CONTENT_LENGTH'])
## s = self.environ['wsgi.input'].read(conlen)
## form = cgi.parse_qs(s)
ctx.__dict__.update(form)
ctx.__dict__.update(vardict)
page(self, ctx)
# Add session cookie to headers, if necessary.
if ishtml and not has_cookie:
for k, v in sorted(cookie.items()):
self.headers.add_header('Set-Cookie', v.OutputString())
start_response('200 OK', self.headers.items())
return self.data
except HttpRedirect, e:
location = e.message
start_response(e.status, [('Location', location)])
return [str(e)]
except HttpError, e:
status = getattr(e, 'status', '500 Internal Server Error')
start_response(status, [('Content-Type', 'text/html')])
return [str(e)]
示例10: make_headers
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
def make_headers(self, headers):
h = Headers([("Allow", "GET, HEAD")])
for item in headers:
h.add_header(item[0], item[1])
return h.items()
示例11: application
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
class application(object):
# don't serve static by default
static_serve = False
static_alias = { '' : 'ketcher.html' }
static_root = None
indigo = None
indigo_inchi = None
def __init__(self, environ, start_response):
self.path = environ['PATH_INFO'].strip('/')
self.method = environ['REQUEST_METHOD']
self.content_type = environ.get('CONTENT_TYPE', '')
self.fields = FieldStorage(fp=environ['wsgi.input'],
environ=environ, keep_blank_values=True)
self.FileWrapper = environ.get('wsgi.file_wrapper', FileWrapper)
self.headers = Headers([])
route = getattr(self, 'on_' + self.path, None)
if route is None:
route = self.serve_static if self.method == 'GET' and \
self.static_serve else self.notsupported
status = "200 OK"
try:
self.response = route()
except self.HttpException as e:
status = e.args[0]
self.response = [e.args[1]]
self.headers.setdefault('Content-Type', 'text/plain')
start_response(status, self.headers.items())
def __iter__(self):
for chunk in self.response:
yield chunk if sys.version_info[0] < 3 or \
not hasattr(chunk, 'encode') else chunk.encode()
def notsupported(self):
raise self.HttpException("405 Method Not Allowed",
"Request not supported")
def indigo_required(method):
def wrapper(self, **args):
if not self.indigo:
raise self.HttpException("501 Not Implemented",
"Indigo libraries are not found")
try:
return method(self, **args)
except indigo.IndigoException as e:
message = str(sys.exc_info()[1])
if 'indigoLoad' in message: # error on load
message = "Cannot load the specified " + \
"structure: %s " % str(e)
raise self.HttpException("400 Bad Request",
message)
return wrapper
@indigo_required
def on_knocknock(self):
return ["You are welcome!"]
@indigo_required
def on_layout(self):
moldata = None
if self.method == 'GET' and 'smiles' in self.fields:
moldata = self.fields.getfirst('smiles')
elif self.is_form_request() and 'moldata' in self.fields:
moldata = self.fields.getfirst('moldata')
selective = 'selective' in self.fields
if moldata:
if '>>' in moldata or moldata.startswith('$RXN'):
rxn = self.indigo.loadQueryReaction(moldata)
if selective:
for mol in rxn.iterateMolecules():
self.selective_layout(mol)
else:
rxn.layout()
return ["Ok.\n",
rxn.rxnfile()]
elif moldata.startswith('InChI'):
mol = self.indigo_inchi.loadMolecule(moldata)
mol.layout()
return ["Ok.\n",
mol.molfile()]
else:
mol = self.indigo.loadQueryMolecule(moldata)
if selective:
for rg in mol.iterateRGroups():
for frag in rg.iterateRGroupFragments():
self.selective_layout(frag)
self.selective_layout(mol)
else:
mol.layout()
return ["Ok.\n",
mol.molfile()]
self.notsupported()
@indigo_required
def on_automap(self):
#.........这里部分代码省略.........
示例12: StaticFile
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
class StaticFile(object):
ACCEPT_GZIP_RE = re.compile(r'\bgzip\b')
BLOCK_SIZE = 16 * 4096
# All mimetypes starting 'text/' take a charset parameter, plus the
# additions in this set
MIMETYPES_WITH_CHARSET = {'application/javascript', 'application/xml'}
CHARSET = 'utf-8'
# Ten years is what nginx sets a max age if you use 'expires max;'
# so we'll follow its lead
FOREVER = 10*365*24*60*60
GZIP_SUFFIX = '.gz'
def __init__(self, path, is_immutable, guess_type=mimetypes.guess_type, **config):
self.path = path
stat = os.stat(path)
self.mtime_tuple = gmtime(stat.st_mtime)
mimetype, encoding = guess_type(path)
mimetype = mimetype or 'application/octet-stream'
charset = self.get_charset(mimetype)
params = {'charset': charset} if charset else {}
self.headers = Headers([
('Last-Modified', formatdate(stat.st_mtime, usegmt=True)),
('Content-Length', str(stat.st_size)),
])
self.headers.add_header('Content-Type', str(mimetype), **params)
if encoding:
self.headers['Content-Encoding'] = encoding
max_age = self.FOREVER if is_immutable else config['max_age']
if max_age is not None:
self.headers['Cache-Control'] = 'public, max-age=%s' % max_age
if config['allow_all_origins']:
self.headers['Access-Control-Allow-Origin'] = '*'
gzip_path = path + self.GZIP_SUFFIX
if os.path.isfile(gzip_path):
self.gzip_path = gzip_path
self.headers['Vary'] = 'Accept-Encoding'
# Copy the headers and add the appropriate encoding and length
self.gzip_headers = Headers(self.headers.items())
self.gzip_headers['Content-Encoding'] = 'gzip'
self.gzip_headers['Content-Length'] = str(os.stat(gzip_path).st_size)
else:
self.gzip_path = self.gzip_headers = None
def get_charset(self, mimetype):
if mimetype.startswith('text/') or mimetype in self.MIMETYPES_WITH_CHARSET:
return self.CHARSET
def serve(self, environ, start_response):
method = environ['REQUEST_METHOD']
if method != 'GET' and method != 'HEAD':
start_response('405 Method Not Allowed', [('Allow', 'GET, HEAD')])
return []
if self.file_not_modified(environ):
start_response('304 Not Modified', [])
return []
path, headers = self.get_path_and_headers(environ)
start_response('200 OK', headers.items())
if method == 'HEAD':
return []
file_wrapper = environ.get('wsgi.file_wrapper', self.yield_file)
fileobj = open(path, 'rb')
return file_wrapper(fileobj)
def file_not_modified(self, environ):
try:
last_requested = environ['HTTP_IF_MODIFIED_SINCE']
except KeyError:
return False
# Exact match, no need to parse
if last_requested == self.headers['Last-Modified']:
return True
return parsedate(last_requested) >= self.mtime_tuple
def get_path_and_headers(self, environ):
if self.gzip_path:
if self.ACCEPT_GZIP_RE.search(environ.get('HTTP_ACCEPT_ENCODING', '')):
return self.gzip_path, self.gzip_headers
return self.path, self.headers
def yield_file(self, fileobj):
# Only used as a fallback in case environ doesn't supply a
# wsgi.file_wrapper
try:
while True:
block = fileobj.read(self.BLOCK_SIZE)
if block:
yield block
else:
break
finally:
fileobj.close()
示例13: __init__
# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import items [as 别名]
class BaseResponse:
"""Base class for Response"""
default_status = 200
default_content_type = 'text/plain;'
def __init__(self, body=b'', status=None, headers=None):
self.headers = Headers()
self._body = body
self._status_code = status or self.default_status
self._cookies = SimpleCookie()
if headers:
for name, value in headers.items():
self.headers.add_header(name, value)
@property
def body(self):
return [self._body]
@property
def status_code(self):
""" The HTTP status code as an integer (e.g. 404)."""
return self._status_code
@property
def status(self):
""" The HTTP status line as a string (e.g. ``404 Not Found``)."""
if not 100 <= self._status_code <= 999:
raise ValueError('Status code out of range.')
status = _HTTP_STATUS_LINES.get(self._status_code)
return str(status or ('{} Unknown'.format(self._status_code)))
@status.setter
def status(self, status_code):
if not 100 <= status_code <= 999:
raise ValueError('Status code out of range.')
self._status_code = status_code
@property
def headerlist(self):
""" WSGI conform list of (header, value) tuples. """
if 'Content-Type' not in self.headers:
self.headers.add_header('Content-Type', self.default_content_type)
if self._cookies:
for c in self._cookies.values():
self.headers.add_header('Set-Cookie', c.OutputString())
return self.headers.items()
def set_cookie(self, key, value, expires=None, max_age=None, path=None,
secret=None, digestmod=hashlib.sha256):
if secret:
if isinstance(secret, str):
secret = secret.encode('utf-8')
encoded = base64.b64encode(pickle.dumps((key, value), pickle.HIGHEST_PROTOCOL))
sig = base64.b64encode(hmac.new(secret, encoded, digestmod=digestmod).digest())
value_bytes = b'!' + sig + b'?' + encoded
value = value_bytes.decode('utf-8')
self._cookies[key] = value
if len(key) + len(value) > 3800:
raise ValueError('Content does not fit into a cookie.')
if max_age is not None:
if isinstance(max_age, int):
max_age_value = max_age
else:
max_age_value = max_age.seconds + max_age.days * 24 * 3600
self._cookies[key]['max-age'] = max_age_value
if expires is not None:
if isinstance(expires, int):
expires_value = expires
else:
expires_value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", expires.timetuple())
self._cookies[key]['expires'] = expires_value
if path:
self._cookies[key]['path'] = path
def delete_cookie(self, key, **kwargs):
kwargs['max_age'] = -1
kwargs['expires'] = 0
self.set_cookie(key, '', **kwargs)