本文整理汇总了Python中six.moves.http_cookies.SimpleCookie类的典型用法代码示例。如果您正苦于以下问题:Python SimpleCookie类的具体用法?Python SimpleCookie怎么用?Python SimpleCookie使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SimpleCookie类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_cookie
def make_cookie(name, load, seed, expire=0, domain="", path="",
timestamp=""):
"""
Create and return a cookie
:param name: Cookie name
:param load: Cookie load
:param seed: A seed for the HMAC function
:param expire: Number of minutes before this cookie goes stale
:param domain: The domain of the cookie
:param path: The path specification for the cookie
:return: A tuple to be added to headers
"""
cookie = SimpleCookie()
if not timestamp:
timestamp = str(int(time.mktime(time.gmtime())))
signature = cookie_signature(seed, load, timestamp)
cookie[name] = "|".join([load, timestamp, signature])
if path:
cookie[name]["path"] = path
if domain:
cookie[name]["domain"] = domain
if expire:
cookie[name]["expires"] = _expiration(expire,
"%a, %d-%b-%Y %H:%M:%S GMT")
return tuple(cookie.output().split(": ", 1))
示例2: _prepare_response
def _prepare_response(self, res_info, url):
res = requests.Response()
res.url = res_info.get('url', url)
res.status_code = res_info.get('status_code', 200)
res.reason_phrase = res_info.get('reason_phrase', REASON_PHRASES.get(res.status_code, 'UNKNOWN STATUS CODE'))
if 'reason' in res_info:
res.reason = res_info['reason']
if 'headers' in res_info:
res.headers.update(res_info['headers'])
if 'Set-Cookie' in res_info['headers'] and 'cookies' not in res_info:
cookies = SimpleCookie()
for entry in res_info['headers']['Set-Cookie'].split(','):
cookies.load(str(entry))
res.cookies.update(cookies)
if 'cookies' in res_info:
res.cookies.update(res_info['cookies'])
res.raw = StreamContent(res_info.get('content', ''))
return res
示例3: cookie_parts
def cookie_parts(name, kaka):
cookie_obj = SimpleCookie(kaka)
morsel = cookie_obj.get(name)
if morsel:
return morsel.value.split("|")
else:
return None
示例4: set_cookie
def set_cookie(name, _, *args):
cookie = SimpleCookie()
cookie[name] = base64.b64encode(":".join(args))
cookie[name]['path'] = "/"
cookie[name]["expires"] = _expiration(5) # 5 minutes from now
logger.debug("Cookie expires: %s", cookie[name]["expires"])
return tuple(cookie.output().split(": ", 1))
示例5: CookieHandler
class CookieHandler(object):
def __init__(self, *args, **kw):
# Somewhere to store cookies between consecutive requests
self.cookies = SimpleCookie()
super(CookieHandler, self).__init__(*args, **kw)
def httpCookie(self, path):
"""Return self.cookies as an HTTP_COOKIE environment value."""
l = [m.OutputString().split(';')[0] for m in self.cookies.values()
if path.startswith(m['path'])]
return '; '.join(l)
def loadCookies(self, envstring):
self.cookies.load(envstring)
def saveCookies(self, response):
"""Save cookies from the response."""
# Urgh - need to play with the response's privates to extract
# cookies that have been set
# TODO: extend the IHTTPRequest interface to allow access to all
# cookies
# TODO: handle cookie expirations
for k, v in response._cookies.items():
k = k.encode('utf8') if bytes is str else k
val = v['value']
val = val.encode('utf8') if bytes is str else val
self.cookies[k] = val
if 'path' in v:
self.cookies[k]['path'] = v['path']
示例6: parse_cookie
def parse_cookie(name, seed, kaka):
"""Parses and verifies a cookie value
:param seed: A seed used for the HMAC signature
:param kaka: The cookie
:return: A tuple consisting of (payload, timestamp)
"""
if not kaka:
return None
cookie_obj = SimpleCookie(kaka)
morsel = cookie_obj.get(name)
if morsel:
parts = morsel.value.split("|")
if len(parts) != 3:
return None
# verify the cookie signature
sig = cookie_signature(seed, parts[0], parts[1])
if sig != parts[2]:
raise SAMLError("Invalid cookie signature")
try:
return parts[0].strip(), parts[1]
except KeyError:
return None
else:
return None
示例7: _assert_cookies_expired
def _assert_cookies_expired(self, http_headers):
cookies_string = ";".join([c[1] for c in http_headers if c[0] == "Set-Cookie"])
all_cookies = SimpleCookie()
all_cookies.load(cookies_string)
now = datetime.datetime.utcnow() #
for c in [self.provider.cookie_name, self.provider.session_cookie_name]:
dt = datetime.datetime.strptime(all_cookies[c]["expires"], "%a, %d-%b-%Y %H:%M:%S GMT")
assert dt < now # make sure the cookies have expired to be cleared
示例8: set_cookie
def set_cookie(self, user):
uid = rndstr(32)
self.uid2user[uid] = user
cookie = SimpleCookie()
cookie[self.cookie_name] = uid
cookie[self.cookie_name]['path'] = "/"
cookie[self.cookie_name]["expires"] = _expiration(480)
logger.debug("Cookie expires: %s", cookie[self.cookie_name]["expires"])
return cookie.output().encode("UTF-8").split(": ", 1)
示例9: cookies
def cookies(self):
if self._cookies is None:
parser = SimpleCookie(self.headers("Cookie"))
cookies = {}
for morsel in parser.values():
cookies[morsel.key] = morsel.value
self._cookies = cookies
return self._cookies.copy()
示例10: cookies
def cookies(self):
if self._cookies is None:
# NOTE(tbug): We might want to look into parsing
# cookies ourselves. The SimpleCookie is doing a
# lot if stuff only required to SEND cookies.
parser = SimpleCookie(self.get_header("Cookie"))
cookies = {}
for morsel in parser.values():
cookies[morsel.key] = morsel.value
self._cookies = cookies
return self._cookies.copy()
示例11: delete_cookie
def delete_cookie(environ, name):
kaka = environ.get("HTTP_COOKIE", "")
logger.debug("delete KAKA: %s", kaka)
if kaka:
cookie_obj = SimpleCookie(kaka)
morsel = cookie_obj.get(name, None)
cookie = SimpleCookie()
cookie[name] = ""
cookie[name]["path"] = "/"
logger.debug("Expire: %s", morsel)
cookie[name]["expires"] = _expiration("dawn")
return tuple(cookie.output().split(": ", 1))
return None
示例12: delete_cookie
def delete_cookie(self, environ):
cookie = environ.get("HTTP_COOKIE", '')
logger.debug("delete cookie: %s", cookie)
if cookie:
_name = self.cookie_name
cookie_obj = SimpleCookie(cookie)
morsel = cookie_obj.get(_name, None)
cookie = SimpleCookie()
cookie[_name] = ""
cookie[_name]['path'] = "/"
logger.debug("Expire: %s", morsel)
cookie[_name]["expires"] = _expiration("now")
return cookie.output().split(": ", 1)
return None
示例13: info_from_cookie
def info_from_cookie(kaka):
logger.debug("KAKA: %s", kaka)
if kaka:
cookie_obj = SimpleCookie(kaka)
morsel = cookie_obj.get("idpauthn", None)
if morsel:
try:
key, ref = base64.b64decode(morsel.value).split(":")
return IDP.cache.uid2user[key], ref
except (KeyError, TypeError):
return None, None
else:
logger.debug("No idpauthn cookie")
return None, None
示例14: get_user
def get_user(self, environ):
cookie = environ.get("HTTP_COOKIE", '')
logger.debug("Cookie: %s", cookie)
if cookie:
cookie_obj = SimpleCookie(cookie)
morsel = cookie_obj.get(self.cookie_name, None)
if morsel:
try:
return self.uid2user[morsel.value]
except KeyError:
return None
else:
logger.debug("No %s cookie", self.cookie_name)
return None
示例15: __init__
def __init__( self ):
"""
Create a new Response defaulting to HTML content and "200 OK" status
"""
self.status = "200 OK"
self.headers = HeaderDict( { "content-type": "text/html" } )
self.cookies = SimpleCookie()