本文整理汇总了Python中six.moves.http_cookies.SimpleCookie方法的典型用法代码示例。如果您正苦于以下问题:Python http_cookies.SimpleCookie方法的具体用法?Python http_cookies.SimpleCookie怎么用?Python http_cookies.SimpleCookie使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.http_cookies
的用法示例。
在下文中一共展示了http_cookies.SimpleCookie方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def __init__(self, options=None):
self.status = '200 OK'
self._headers = {}
self.options = ResponseOptions() if options is None else options
# NOTE(tbug): will be set to a SimpleCookie object
# when cookie is set via set_cookie
self._cookies = None
self._media = None
self.body = None
self.data = None
self.stream = None
self.stream_len = None
if self.context_type is None:
# PERF(kgriffs): The literal syntax is more efficient than dict().
self.context = {}
else:
self.context = self.context_type()
示例2: unset_cookie
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def unset_cookie(self, name):
"""Unset a cookie in the response
Clears the contents of the cookie, and instructs the user
agent to immediately expire its own copy of the cookie.
Warning:
In order to successfully remove a cookie, both the
path and the domain must match the values that were
used when the cookie was created.
"""
if self._cookies is None:
self._cookies = SimpleCookie()
self._cookies[name] = ''
# NOTE(Freezerburn): SimpleCookie apparently special cases the
# expires attribute to automatically use strftime and set the
# time as a delta from the current time. We use -1 here to
# basically tell the browser to immediately expire the cookie,
# thus removing it from future request objects.
self._cookies[name]['expires'] = -1
示例3: get_cookie
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def get_cookie(res, cookie_name):
headers = res.headers.to_list()
set_cookie_strings = [h for h in headers if (
h[0] == 'Set-Cookie' and cookie_name in h[1]
)]
try:
cookie_string = set_cookie_strings[0][1]
except IndexError as e:
print(cookie_name)
for header in headers:
print(header)
print(set_cookie_strings)
raise e
cookie = http_cookies.SimpleCookie(cookie_string)
access_granted_cookie = cookie[list(cookie.keys())[0]].value
return access_granted_cookie
示例4: __init__
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def __init__(self):
self.status = '200 OK'
self._headers = {}
# NOTE(tbug): will be set to a SimpleCookie object
# when cookie is set via set_cookie
self._cookies = None
self.body = None
self.data = None
self.stream = None
self.stream_len = None
if self.context_type is None:
# PERF(kgriffs): The literal syntax is more efficient than dict().
self.context = {}
else:
self.context = self.context_type()
示例5: cookies
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
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()
示例6: update_cookies
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def update_cookies(base_value, cookies):
cookie = SimpleCookie(base_value)
for k, v in cookies.items():
cookie[k] = v
return cookie.output(header='', sep=';').lstrip()
示例7: new_websocket_client
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def new_websocket_client(self):
# The nova expected behavior is to have token
# passed to the method GET of the request
parse = urlparse.urlparse(self.path)
query = parse.query
token = urlparse.parse_qs(query).get("token", [""]).pop()
if not token:
# NoVNC uses it's own convention that forward token
# from the request to a cookie header, we should check
# also for this behavior
hcookie = self.headers.getheader('cookie')
if hcookie:
cookie = Cookie.SimpleCookie()
cookie.load(hcookie)
if 'token' in cookie:
token = cookie['token'].value
resp, body = self._nova_client.client.get(
'/os-console-auth-tokens/%s' % token)
# TODO check response
connect_info = body['console']
host = connect_info['host']
port = connect_info['port']
internal_access_path = connect_info['internal_access_path']
mks_auth = json.loads(internal_access_path)
ticket = mks_auth['ticket']
cfg_file = mks_auth['cfgFile']
thumbprint = mks_auth['thumbprint']
tsock = handshake(host, port, ticket, cfg_file, thumbprint)
# Start proxying
try:
self.do_proxy(tsock)
except Exception:
if tsock:
tsock.shutdown(socket.SHUT_RDWR)
tsock.close()
self.vmsg("%(host)s:%(port)s: Target closed" %
{'host': host, 'port': port})
raise
示例8: _cookie_replacer
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def _cookie_replacer(self, match):
"""Replace a regex match with the cookie of a previous response."""
case = match.group('case')
if case:
referred_case = self.history[case]
else:
referred_case = self.prior
response_cookies = referred_case.response['set-cookie']
cookies = http_cookies.SimpleCookie()
cookies.load(response_cookies)
cookie_string = cookies.output(attrs=[], header='', sep=',').strip()
return cookie_string
示例9: __init__
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def __init__(self, autologin_url, crawler):
self.crawler = crawler
s = crawler.settings
self.passed_setting = {
name: s.get(name) for name in [
'SPLASH_URL', 'USER_AGENT', 'HTTP_PROXY', 'HTTPS_PROXY']
if s.get(name)}
self.autologin_url = autologin_url
self.login_url = s.get('AUTOLOGIN_LOGIN_URL')
self.username = s.get('AUTOLOGIN_USERNAME')
self.password = s.get('AUTOLOGIN_PASSWORD')
self.extra_js = s.get('AUTOLOGIN_EXTRA_JS')
self.autologin_download_delay = s.get('AUTOLOGIN_DOWNLOAD_DELAY')
self.logout_url = s.get('AUTOLOGIN_LOGOUT_URL')
self.check_logout = s.getbool('AUTOLOGIN_CHECK_LOGOUT', True)
# _force_skip and _n_pend and for testing only
self._force_skip = s.getbool('_AUTOLOGIN_FORCE_SKIP')
self._n_pend = s.getint('_AUTOLOGIN_N_PEND')
self._login_df = None
self.max_logout_count = s.getint('AUTOLOGIN_MAX_LOGOUT_COUNT', 4)
auth_cookies = s.get('AUTOLOGIN_COOKIES')
self.skipped = False
self.stats = crawler.stats
if auth_cookies:
cookies = SimpleCookie()
cookies.load(auth_cookies)
self.auth_cookies = [
{'name': m.key, 'value': m.value} for m in cookies.values()]
self.logged_in = True
else:
self.auth_cookies = None
self.logged_in = False
示例10: send
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def send(self, url, method="GET", **kwargs):
_kwargs = copy.copy(self.request_args)
if kwargs:
_kwargs.update(kwargs)
if self.cookiejar:
_cd = self.cookies(url)
if _cd:
_kwargs["cookies"] = _cd
if self.user and self.passwd:
_kwargs["auth"] = (self.user, self.passwd)
if "headers" in _kwargs and isinstance(_kwargs["headers"], list):
if DICT_HEADERS:
# requests.request wants a dict of headers, not a list of tuples
_kwargs["headers"] = dict(_kwargs["headers"])
try:
logger.debug("%s to %s", method, url)
for arg in ["cookies", "data", "auth"]:
try:
logger.debug("%s: %s", arg.upper(), _kwargs[arg])
except KeyError:
pass
r = requests.request(method, url, **_kwargs)
logger.debug("Response status: %s", r.status_code)
except requests.ConnectionError as exc:
raise ConnectionError("%s" % exc)
try:
self.set_cookie(SimpleCookie(r.headers["set-cookie"]), r)
except AttributeError:
pass
except KeyError:
pass
return r
示例11: make_cookie
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
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))
示例12: parse_cookie
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
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
示例13: cookie_parts
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
def cookie_parts(name, kaka):
cookie_obj = SimpleCookie(kaka)
morsel = cookie_obj.get(name)
if morsel:
return morsel.value.split("|")
else:
return None
示例14: info_from_cookie
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
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
示例15: set_cookie
# 需要导入模块: from six.moves import http_cookies [as 别名]
# 或者: from six.moves.http_cookies import SimpleCookie [as 别名]
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))
# ----------------------------------------------------------------------------
# map urls to functions