import itertools import hmac import time import zlib import time def peek_iter(iterable): try: first = next(iterable) except StopIteration: return None return itertools.chain([first], iterable) def split_prefix(key, prefixs): for p in prefixs: if key.startswith(p): plen = len(p) return (key[:plen], key[plen:]) def create_decompressor(): return zlib.decompressobj(16 + zlib.MAX_WBITS) class HMACCookieMaker: def __init__(self, key, name): self.key = key self.name = name def __call__(self, duration, extraId = ''): expire = str(long(time.time() + duration)) if extraId: msg = extraId + '-' + expire else: msg = expire hmacdigest = hmac.new(self.key, msg) hexdigest = hmacdigest.hexdigest() if extraId: cookie = '{0}-{1}={2}-{3}'.format(self.name, extraId, expire, hexdigest) else: cookie = '{0}={1}-{2}'.format(self.name, expire, hexdigest) return cookie #return cookie + hexdigest # Adapted from example at class PerfTimer: def __init__(self, perfdict, name): self.perfdict = perfdict self.name = name def __enter__(self): self.start = time.clock() return self def __exit__(self, *args): self.end = time.clock() if self.perfdict is not None: self.perfdict[self.name] = str(self.end - self.start) # adapted from wsgiref.request_uri, but doesn't include domain name and allows ':' in url def request_uri(environ, include_query=1): """Return the requested path, optionally including the query string""" from urllib import quote url = quote(environ.get('SCRIPT_NAME', '')+environ.get('PATH_INFO',''),safe='/;=,:') if include_query and environ.get('QUERY_STRING'): url += '?' + environ['QUERY_STRING'] return url