本文整理汇总了Python中Cookie.SimpleCookie.load方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleCookie.load方法的具体用法?Python SimpleCookie.load怎么用?Python SimpleCookie.load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cookie.SimpleCookie
的用法示例。
在下文中一共展示了SimpleCookie.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_cookie_dict
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def get_cookie_dict(environ):
"""Return a *plain* dictionary of cookies as found in the request.
Unlike ``get_cookies`` this returns a dictionary, not a
``SimpleCookie`` object. For incoming cookies a dictionary fully
represents the information. Like ``get_cookies`` this caches and
checks the cache.
"""
header = environ.get('HTTP_COOKIE')
if not header:
return {}
if environ.has_key('paste.cookies.dict'):
cookies, check_header = environ['paste.cookies.dict']
if check_header == header:
return cookies
cookies = SimpleCookie()
try:
cookies.load(header)
except CookieError:
pass
result = {}
for name in cookies:
result[name] = cookies[name].value
environ['paste.cookies.dict'] = (result, header)
return result
示例2: get_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def get_cookie(self, name):
cookie_str = self.request.headers.get('cookie')
if not cookie_str:
return None
cookie = SimpleCookie()
cookie.load(cookie_str)
return cookie[name].value;
示例3: __get_params
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def __get_params(self):
self._kwargs = self.__get_query_params()
self._cog_ajax = self._kwargs.get('cog_ajax')
self.__cog_target = self._kwargs.get('cog_target')
self._cog_raw = self._kwargs.get('cog_raw', None)
self._cog_method = self._kwargs.get('cog_method', None)
# cog_method must not contain non-word caracters
assert self._cog_method is None or \
re.search('\W', self._cog_method) is None
if self._cog_method is not None and self._cog_method[0] == '_':
# we never should receive a protected method...
self._cog_method = "w3error"
self._kwargs['cog_method'] = "w3error"
self._kwargs['cog_error'] = "Can't call a protected method!"
self._cog_ref_oid = self._kwargs.get('cog_ref_oid', None)
self._cog_oid_ = self._kwargs.get('cog_oid_', None)
self._session_key = None
if 'HTTP_COOKIE' in self._environ:
cookie_string = self._environ.get('HTTP_COOKIE')
cookie = SimpleCookie()
cookie.load(cookie_string)
if 'cog_session' in cookie:
self._session_key = cookie['cog_session'].value
self.__cog_environment = self.__get_env()
self._cog_fqtn_ = self._kwargs.get('cog_fqtn_', None)
if self._cog_ref_oid and self._cog_ref_oid == self._cog_oid_:
self._cog_oid_ = None
self._kwargs['cog_controller'] = self
self._kwargs['cog_first_call'] = True
示例4: is_present
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def is_present(mpkt):
hdrs = mpkt.cfields.get('dissector.http.headers', None)
if not hdrs:
return False
if 'cookie' in hdrs:
for cstr in hdrs['cookie']:
cookie = SimpleCookie()
cookie.load(cstr)
for k, mar in cookie.items():
cookies[k].append(mar.value)
return True
elif 'set-cookie' in hdrs:
for cstr in hdrs['set-cookie']:
cookie = SimpleCookie()
cookie.load(cstr)
for k, mar in cookie.items():
cookies[k].append(mar.value)
return True
return False
示例5: getSessionId
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def getSessionId(request_cookie):
cookie = SimpleCookie()
cookie.load(request_cookie)
try:
sessionId = int((cookie['id']).value)
except CookieError, ValueError:
sessionId = sessions.AddNewSession({'num' : 0, 'auth' : False})
示例6: __init__
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
class cookie:
def __init__( self ):
self.cookieObj = SimpleCookie()
self.load()
def load( self ):
if not os.environ.has_key("HTTP_COOKIE"):
# Kein Cookie vorhanden
return
self.cookieObj.load( os.environ["HTTP_COOKIE"] )
def readCookie( self, CookieName ):
if self.cookieObj == False:
# Gibt kein Cookie
return False
if self.cookieObj.has_key(CookieName):
return self.cookieObj[CookieName].value
else:
return False
def debug( self ):
print "Cookie-Debug:"
print "<hr><pre>"
if not os.environ.has_key("HTTP_COOKIE"):
print "There is no HTTP_COOKIE in os.environ:\n"
for k,v in os.environ.iteritems(): print k,v
else:
print self.cookieObj
print "</pre><hr>"
示例7: username
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def username(cookie, name=None):
""" try to extract username from PAS cookie """
if cookie is not None:
cookies = SimpleCookie()
try:
cookies.load(cookie)
except CookieError:
return name
if cookie_name in cookies:
# Deal with doubly quoted cookies
ac_cookie = repeatedly_unquote(cookies[cookie_name].value)
try:
ac = decodestring(ac_cookie + '=====')
except (TypeError, binascii.Error):
return name
# plone.session 3.x (Plone 4.x)
if '!' in ac[40:]:
name, user_data = ac[40:].split('!', 1)
# plone.session 2.x (Plone 3.x)
elif ' ' in ac[20:21]:
name = ac[21:]
# PluggableAuthService.CookieAuthHelper
elif ':' in ac:
user, pwd = ac.split(':', 1)
# PluggableAuthService >= 1.5
try:
name = user.decode('hex')
# PluggableAuthService < 1.5
except TypeError:
name = user
return name
示例8: CookieHandler
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
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')
self.cookies[k] = v['value'].encode('utf8')
if 'path' in v:
self.cookies[k]['path'] = v['path']
示例9: BaseHeaders
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
class BaseHeaders(CaseInsensitiveMapping):
"""Represent the headers in an HTTP Request or Response message.
"""
def __init__(self, raw):
"""Takes headers as a string.
"""
def genheaders():
for line in raw.splitlines():
k, v = line.split(':', 1)
yield k.strip(), v.strip()
CaseInsensitiveMapping.__init__(self, genheaders)
# Cookie
# ======
self.cookie = SimpleCookie()
try:
self.cookie.load(self.get('Cookie', ''))
except CookieError:
pass # XXX really?
def raw(self):
"""Return the headers as a string, formatted for an HTTP message.
"""
out = []
for header, values in self.iteritems():
for value in values:
out.append('%s: %s' % (header, value))
return '\r\n'.join(out)
raw = property(raw)
示例10: CookieScraper
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
class CookieScraper(object):
"Scraper that keeps track of getting and setting cookies."
def __init__(self):
self._cookies = SimpleCookie()
def get_page(self, url, post_data=None, headers=()):
"""
Helper method that gets the given URL, handling the sending and storing
of cookies. Returns the requested page as a string.
"""
socket.timeout(300)
opener = urllib.URLopener()
opener.addheader('Cookie', self._cookies.output(attrs=[], header='',
sep=';').strip())
for k, v in headers:
opener.addheader(k, v)
try:
f = opener.open(url, post_data)
except IOError, e:
if e[1] == 302:
# Got a 302 redirect, but check for cookies before redirecting.
# e[3] is a httplib.HTTPMessage instance.
if e[3].dict.has_key('set-cookie'):
self._cookies.load(e[3].dict['set-cookie'])
return self.get_page(e[3].getheader('location'))
else:
raise
if f.headers.dict.has_key('set-cookie'):
self._cookies.load(f.headers.dict['set-cookie'])
return f.read()
示例11: Headers
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
class Headers(BaseHeaders):
"""Model headers in an HTTP Request message.
"""
def __init__(self, raw):
"""Extend BaseHeaders to add extra attributes.
"""
BaseHeaders.__init__(self, raw)
# Cookie
# ======
self.cookie = SimpleCookie()
try:
self.cookie.load(self.get('Cookie', ''))
except CookieError:
pass # XXX really?
# Host
# ====
# Per the spec, respond with 400 if no Host header is given. However,
# we prefer X-Forwarded-For if that is available.
host = self.get('X-Forwarded-Host', self['Host']) # KeyError raises 400
self.host = UnicodeWithRaw(host, encoding='idna')
# Scheme
# ======
# http://docs.python.org/library/wsgiref.html#wsgiref.util.guess_scheme
scheme = 'https' if self.get('HTTPS', False) else 'http'
self.scheme = UnicodeWithRaw(scheme)
示例12: cookies
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def cookies(self, rawdata):
"""Set Response Cookies.
:param rawdata: (str or dict). List of `cookielib.Cookie`.
"""
sc = SimpleCookie()
sc.load(rawdata)
self._cookies = sc.items()
示例13: cookies
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def cookies(self):
from Cookie import SimpleCookie
cookie = SimpleCookie()
cookie.load(self.environ.get('HTTP_COOKIE', ''))
result = {}
for key, value in cookie.iteritems():
result[key] = value
return result
示例14: get_cookies
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def get_cookies(str):
cookie = SimpleCookie()
cookie.load(str)
cookies = {}
for key, morsel in cookie.items():
cookies[key] = morsel.value
return cookies
示例15: test_cookie_credentials_plaintext
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import load [as 别名]
def test_cookie_credentials_plaintext(self):
fetch_arguments = build_fetch_arguments("/foobar")
credentials = CookieCredentials("auth", "token")
credentials(fetch_arguments)
cookie = SimpleCookie()
cookie.load(fetch_arguments.headers["Cookie"])
self.assertTrue("auth" in cookie)
self.assertEqual("token", cookie["auth"].value)