本文整理汇总了Python中Cookie.SimpleCookie类的典型用法代码示例。如果您正苦于以下问题:Python SimpleCookie类的具体用法?Python SimpleCookie怎么用?Python SimpleCookie使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SimpleCookie类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getSessionId
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})
示例2: __read_cookie
def __read_cookie(self):
"""Reads the HTTP Cookie and loads the sid and data from it (if any)."""
try:
# check the cookie to see if a session has been started
cookie = SimpleCookie(os.environ['HTTP_COOKIE'])
self.cookie_keys = filter(is_gaesessions_key, cookie.keys())
if not self.cookie_keys:
return # no session yet
self.cookie_keys.sort()
data = ''.join(cookie[k].value for k in self.cookie_keys)
i = SIG_LEN + SID_LEN
sig, sid, b64pdump = data[:SIG_LEN], data[SIG_LEN:i], data[i:]
pdump = b64decode(b64pdump)
actual_sig = Session.__compute_hmac(self.base_key, sid, pdump)
if sig == actual_sig:
self.__set_sid(sid, False)
# check for expiration and terminate the session if it has expired
if self.get_expiration() != 0 and time.time() > self.get_expiration():
return self.terminate()
if pdump:
self.data = self.__decode_data(pdump)
else:
self.data = None # data is in memcache/db: load it on-demand
else:
logging.warn('cookie with invalid sig received from %s: %s' % (os.environ.get('REMOTE_ADDR'), b64pdump))
except (CookieError, KeyError, IndexError, TypeError):
# there is no cookie (i.e., no session) or the cookie is invalid
self.terminate(False)
示例3: 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 Exception("Invalid cookie signature")
try:
return parts[0].strip(), parts[1]
except KeyError:
return None
else:
return None
示例4: cookie
def cookie(name, sid, seed, expire=0, domain="", path=""):
"""
Create and return a cookie
:param sid: Session identifier
: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()
timestamp = str(int(time.mktime(time.gmtime())))
#print >> sys.stderr, "COOKIE create '%s' '%s' '%s'" % (seed, sid,
# timestamp)
signature = cookie_signature(seed, sid, timestamp)
#print >> sys.stderr, ">>", signature
cookie[name] = "|".join([sid, 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))
示例5: __login
def __login(self, username, password):
"""
login douban, get the session token
"""
data = urllib.urlencode({'source':'simple',
'form_email':username, 'form_password':password})
contentType = "application/x-www-form-urlencoded"
self.__get_bid()
cookie = "bid=%s" % self.bid
headers = {"Content-Type":contentType, "Cookie": cookie }
with contextlib.closing(httplib.HTTPSConnection("www.douban.com")) as conn:
conn.request("POST", "/accounts/login", data, headers)
r1 = conn.getresponse()
resultCookie = SimpleCookie(r1.getheader('Set-Cookie'))
if not resultCookie.has_key('dbcl2'):
raise DoubanLoginException()
dbcl2 = resultCookie['dbcl2'].value
if dbcl2 is not None and len(dbcl2) > 0:
self.dbcl2 = dbcl2
uid = self.dbcl2.split(':')[0]
self.uid = uid
示例6: username
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
示例7: getSession
def getSession(self):
"""Return the existing session or a new session"""
if self.session is not None:
return self.session
# Get value of cookie header that was sent
cookie_str = self.headers.get('Cookie')
if cookie_str:
cookie_obj = SimpleCookie(cookie_str)
sid_morsel = cookie_obj.get(self.SESSION_COOKIE_NAME, None)
if sid_morsel is not None:
sid = sid_morsel.value
else:
sid = None
else:
sid = None
# If a session id was not set, create a new one
if sid is None:
sid = randomString(16, '0123456789abcdef')
session = None
else:
session = self.server.sessions.get(sid)
# If no session exists for this session ID, create one
if session is None:
session = self.server.sessions[sid] = {}
session['id'] = sid
self.session = session
return session
示例8: __get_params
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
示例9: __read_cookies
def __read_cookies(self):
from Cookie import SimpleCookie
cookies_raw = SimpleCookie(self.get_env('HTTP_COOKIE'))
cookies = {}
for key, field in cookies_raw.iteritems():
cookies[key] = field.value
return Table(cookies, allow_duplicates = False, readonly = True)
示例10: application
def application(environ, start_response):
GET = parse_qs(environ['QUERY_STRING'])
path = environ['PATH_INFO']
cookies = SimpleCookie(environ.get('HTTP_COOKIE', ''))
headers = {'Content-Type': 'text/html'}
if path == '/':
response = base%{'contenido': form}
elif path == '/set':
cookies['sessionId'] = store.add(GET.get('name', ['NULL McNULL',])[0])
response = base%{'contenido': '<div style="background-color:green;color:white">Cookie establecida</div>'}
headers.update({'Set-Cookie': cookies['sessionId'].OutputString()})
else:
cookie = cookies.get('sessionId',None)
name = cookie and store.get(cookie.value, None) or None
response = base%{'contenido': "<p>El valor de la sesión es: %s</p>"%name if name else 'Ninguno'}
headers.update({'Content-Length': str(len(response))})
start_response(
"200 OK",
headers.items()
)
return [response]
示例11: __read_cookie
def __read_cookie(self):
"""Reads the HTTP Cookie and loads the sid and data from it (if any)."""
print 'session: __read_cookie'
try:
if self.environ.get('HTTP_COOKIE') is None:
return #no cookies
#cookie = SimpleCookie(os.environ['HTTP_COOKIE'])
cookie = SimpleCookie(self.environ.get('HTTP_COOKIE'))
self.cookie_keys = filter(is_mole_sessions_key, cookie.keys())
if not self.cookie_keys:
return # no session
self.cookie_keys.sort()
data = ''.join(cookie[k].value for k in self.cookie_keys)
i = SIG_LEN + SID_LEN
sig, sid, b64pdump = data[:SIG_LEN], data[SIG_LEN:i], data[i:]
pdump = b64decode(b64pdump)
actual_sig = Session.__compute_hmac(self.base_key, sid, pdump)
if sig == actual_sig:
self.__set_sid(sid, False)
if self.get_expiration() != 0 and time.time() > self.get_expiration():
return self.terminate()
if pdump:
self.data = self.__decode_data(pdump)
else:
self.data = None
else:
logging.warn('cookie with invalid sig received from %s: %s' % (os.environ.get('REMOTE_ADDR'), b64pdump))
except (CookieError, KeyError, IndexError, TypeError):
import traceback;traceback.print_exc()
logging.error("session error:", exc_info=True)
self.terminate(False)
示例12: start
def start(self, cookies, cookieopts=None):
c = SimpleCookie(cookies)
sid = c.get(self.cookiename)
create = True
if sid is not None:
for m in self.get(sid.value):
yield m
if self.apiroutine.retvalue is not None:
self.apiroutine.retvalue = (self.SessionHandle(self.apiroutine.retvalue, self.apiroutine), [])
create = False
if create:
for m in self.create():
yield m
sh = self.apiroutine.retvalue
m = Morsel()
m.key = self.cookiename
m.value = sh.id
m.coded_value = sh.id
opts = {"path": "/", "httponly": True}
if cookieopts:
opts.update(cookieopts)
if not cookieopts["httponly"]:
del cookieopts["httponly"]
m.update(opts)
self.apiroutine.retvalue = (sh, [m])
示例13: getSession
def getSession(self):
"""Return the existing session or a new session"""
if self.session is not None:
return self.session
# Get value of cookie header that was sent
cookie_str = self.headers.get('Cookie')
if cookie_str:
cookie_obj = SimpleCookie(cookie_str)
sid_morsel = cookie_obj.get(self.SESSION_COOKIE_NAME, None)
if sid_morsel is not None:
sid = sid_morsel.value
else:
sid = None
else:
sid = None
# If a session id was not set, create a new one
if sid is None:
# Pure pragmatism: Use function for nonce salt to generate session ID.
sid = make_nonce_salt(16)
session = None
else:
session = self.server.sessions.get(sid)
# If no session exists for this session ID, create one
if session is None:
session = self.server.sessions[sid] = {}
session['id'] = sid
self.session = session
return session
示例14: get_cookie
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;
示例15: __init__
def __init__(self, hnd, name = session.COOKIE_NAME, timeout = 0):
super(DatastoreSession, self).__init__(hnd, name, timeout)
SessionStore.clear()
# check from cookie
if not timeout:
config = Config()
timeout = config.get('session_timeout', 60*60)
elif timeout == -1:
timeout = 356*24*60*60*50
if name in hnd.request.cookies:
self._id = hnd.request.cookies[name]
res = SessionStore.gql("WHERE id = :1", self._id).get()
if res:
self._store = res
session_data = self._store.value
if session_data:
self.update(pickle.loads(session_data))
else:
self._create_store(self._id)
else: # not in the cookie, set it
c = SimpleCookie()
c[name] = self._id
c[name]['path'] = '/'
c[name]['expires'] = rfc822.formatdate(time()+timeout)
cs = c.output().replace('Set-Cookie: ', '')
hnd.response.headers.add_header('Set-Cookie', cs)
self._create_store(self._id)