本文整理汇总了Python中Cookie.SimpleCookie.keys方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleCookie.keys方法的具体用法?Python SimpleCookie.keys怎么用?Python SimpleCookie.keys使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cookie.SimpleCookie
的用法示例。
在下文中一共展示了SimpleCookie.keys方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_requests_from_url
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def make_requests_from_url(self,url):
try:
course_id = re.findall(r'class.coursera.org/(.*)/class',url)[0]
except IndexError:
print "unrecognizable coursera course URL, because course id cannot be extracted"
return
forum_url = "http://class.coursera.org/%s/forum/index" %course_id
print forum_url
headers = self._load_header()
cookie_string = headers["Cookie"]
del headers["Cookie"]
cookie = SimpleCookie(cookie_string)
print headers
print cookie.keys()
return Request(forum_url, headers = headers, cookies = cookie)
示例2: __read_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
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)
示例3: __read_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
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)
示例4: __get__
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def __get__(self, item, cls):
if len(self) == 0:
c = SimpleCookie(app.request.get('HTTP_COOKIE', ''))
# TODO Fix for GAE
for key in c.keys():
self[key] = c.get(key).value
return self
示例5: parse_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def parse_cookie(cookie):
if cookie == '':
return {}
c = SimpleCookie()
c.load(cookie)
cookiedict = {}
for key in c.keys():
cookiedict[key] = c.get(key).value
return cookiedict
示例6: COOKIES
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def COOKIES(self):
if 'CORE_COOKIES' not in self:
c = SimpleCookie(self.get('HTTP_COOKIE', ''))
cd = {}
# TODO Fix for GAE
for key in c.keys():
cd[key] = c.get(key).value
self['CORE_COOKIES'] = Hashmap(cd)
return self['CORE_COOKIES']
示例7: parse_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def parse_cookie(cookie):
""" borrowed from django.http """
if cookie == '':
return {}
try:
c = SimpleCookie()
c.load(cookie)
except CookieError:
return {}
cookiedict = {}
for key in c.keys():
cookiedict[key] = c.get(key).value
return cookiedict
示例8: renderPage
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def renderPage(self):
cookie = SimpleCookie(os.environ['HTTP_COOKIE'])
printout = ''
self.cookie_keys = cookie.keys()
if not self.cookie_keys:
self.response.out.write('No session yet')
return
self.cookie_keys.sort()
data = ''.join(cookie[k].value for k in self.cookie_keys)
printout += data + '\n\n\n'
i = gaesessions.SIG_LEN + gaesessions.SID_LEN
sig, b64pdump = data[:gaesessions.SIG_LEN], data[i:]
printout += 'sig = ' + sig + '\n'
b64pdump += "=" * ((4 - len(b64pdump) % 4) % 4)
printout += 'len = ' + str(len(b64pdump)) + '\n'
printout += 'padding = ' + str(((4 - len(b64pdump) % 4) % 4)) + '\n\n'
try:
pdump = b64decode(b64pdump)
if pdump:
printout += printdict(decode_data(pdump))
else:
printout += 'data is in memcache/db: load it on-demand'
except:
lens = len(b64pdump)
lenx = lens - (lens % 4 if lens % 4 else 4)
try:
printout += b64decode(b64pdump[:lenx])
except:
printout += str(sys.exc_info())
session = sessionmanager.getsession(self)
template_values = {
'appId': conf.FBAPI_APP_ID,
'token': session['access_token'],
'app': session['appid'],
'conf': conf,
'me': session['me'],
'cookie': printout,
'isdesktop': session and session['isdesktop'] or False,
'header': '',
'code': self.request.get('code', None) }
root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
self.response.out.write(template.render(os.path.join(root, 'admin/templates/dumpcookie.html'), template_values))
self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
示例9: parse_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def parse_cookie(cookie):
if cookie == '':
return {}
try:
c = SimpleCookie()
c.load(cookie)
except CookieError:
# Invalid cookie
return {}
cookiedict = {}
for key in c.keys():
cookiedict[key] = c.get(key).value
return cookiedict
示例10: Response
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
class Response(object):
"""
Describes an HTTP response. Currently very simple since the actual body
of the request is handled separately.
"""
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()
def set_content_type(self, type):
"""
Sets the Content-Type header
"""
self.headers["content-type"] = type
def get_content_type(self):
return self.headers["content-type"]
def send_redirect(self, url):
"""
Send an HTTP redirect response to (target `url`)
"""
raise httpexceptions.HTTPFound(url.encode("utf-8"), headers=self.wsgi_headeritems())
def wsgi_headeritems(self):
"""
Return headers in format appropriate for WSGI `start_response`
"""
result = self.headers.headeritems()
# Add cookie to header
for name in self.cookies.keys():
crumb = self.cookies[name]
header, value = str(crumb).split(": ", 1)
result.append((header, value))
return result
def wsgi_status(self):
"""
Return status line in format appropriate for WSGI `start_response`
"""
if isinstance(self.status, int):
exception = httpexceptions.get_exception(self.status)
return "%d %s" % (exception.code, exception.title)
else:
return self.status
示例11: get_the_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def get_the_cookie(url, username=None, password=None):
req = urlopen(url)
data = req.read()
hidden_inputs = re.findall('<INPUT.*HIDDEN.*NAME="(.*)".*VALUE="(.*)">', data)
if username is None:
username = raw_input('Username: ')
if password is None:
password = getpass()
hidden_inputs.append(('username', username))
hidden_inputs.append(('passcode', password))
qs = urlencode(hidden_inputs)
action = urljoin(url, re.findall('<FORM action="([^"]*)" .*>', data)[0])
req2 = urlopen(action, data=qs)
cookie = SimpleCookie(req2.info()['set-cookie'])
return cookie.keys()[0] + "=" + cookie.values()[0].value
示例12: load_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def load_cookie(self, cookie_string):
"""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(cookie_string)
logging.info("JUST GOT COOKIE WHICH IS: {}".format(cookie))
self.cookie_keys = filter(is_gaesessions_key, cookie.keys())
if not self.cookie_keys:
logging.info("NO APPROPRIATE KEYS")
return # no session yet
self.cookie_keys.sort()
logging.info("THE KEYS: {}".format(self.cookie_keys))
data = "".join(cookie[k].value for k in self.cookie_keys)
logging.info("DATA: {}".format(data))
i = SIG_LEN + SID_LEN
logging.info("i: {}".format(i))
sig, sid, b64pdump = data[:SIG_LEN], data[SIG_LEN:i], data[i:]
logging.info("sig: {}".format(sig))
logging.info("sid: {}".format(sid))
logging.info("b64pdump: {}".format(b64pdump))
pdump = b64decode(b64pdump)
actual_sig = Session.__compute_hmac(self.base_key, sid, pdump)
if sig == actual_sig:
logging.info("SIG MATCH")
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():
logging.info("EXPIRED")
return self.terminate()
if pdump:
logging.info("LOADING NEW DATA")
self.data = self.__decode_data(pdump)
else:
logging.info("SETTING NONE DATA")
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), e:
logging.info("OOPSIE: {}".format(e))
logging.info(traceback.print_exc(e))
# there is no cookie (i.e., no session) or the cookie is invalid
self.terminate(False)
示例13: __call__
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
def __call__(self, environ, start_response):
self.set_profiling()
rv = self.application(environ, start_response)
t_p = self.start_profile()
request = environ.get("request", {})
headers = request.get("headers", [])
sesconf = self.sesconf
# if expireAllSessions command is set, expire all sessions
if commandQueue.get("expireAllSessions", False):
self.del_all()
command("expireAllSessions", False)
self.end_profile("ses1", environ, t_p)
# if request is done skip execution of this module
if request.get("done", False):
self.end_profile("session-handler", environ, t_p)
return rv
# timeout expired sessions
# self.cleanup(request)
expires = request["now"] + datetime.timedelta(seconds=int(sesconf.get("timeout", 60*60*24)))
# load cookie
cookie = SimpleCookie(environ.get('HTTP_COOKIE'))
cookie_name = sesconf.get("cookie_name", "SID")
cookie_path = sesconf.get("cookie_path", "/")
cookie_secure = sesconf.get("cookie_secure", "yes")
cookie_support = len(cookie.keys())
data = cookie.get(cookie_name, None)
self.end_profile("ses2", environ, t_p)
if data:
cookie_support = "ok"
#print "cookie data found, trying to load session %s" % str(data.value)
# session id found in cookie, attempt to load session
request["session"] = self.load_session(data.value)
if request["session"]:
request["session"].expires = expires
cookie[cookie_name]["expires"] = expires.ctime()
cookie[cookie_name]['path'] = cookie_path
if(cookie_secure == "yes"):
cookie[cookie_name]['secure'] = True
if (not data or not request["session"]) and cookie_support:
sid = self.generate_id()
#log.error(
# "Creating new session object for %s, %s, cookie status: %s, sessions: %s" %
# (sid, str(request), str(data), self.cache.keys())
#)
# session id not foind in cookie, create new session and send cookie data
self.cache[sid] = SessionObject(
id = sid, expires = expires
)
if self.profile:
profile["sessions"] += 1
request["session"] = self.load_session(sid)
request["created_session"] = sid
cookie[cookie_name] = sid
cookie[cookie_name]["expires"] = expires.ctime()
cookie[cookie_name]['path'] = cookie_path
if(cookie_secure == "yes"):
cookie[cookie_name]['secure'] = True
#print "Cookie set for %s" % str(sid)
elif not cookie_support:
request["session"] = SessionObject(id=self.generate_id(), expires=expires)
cookie["cookie_ok"] = "ok"
cookie["cookie_ok"]["path"] = "/"
if(cookie_secure == "yes"):
cookie["cookie_ok"]['secure'] = True
request["cookies_out"]["cookie_ok"] = cookie
#cookie["cookie_ok"]["expires"] = expires.ctime()
#print "Cookie support not established yet, no session object stored"
self.end_profile("ses3", environ, t_p)
request["cookies_out"][cookie_name] = cookie
#headers.append(('Set-Cookie', cookie[cookie_name].OutputString()))
#.........这里部分代码省略.........
示例14: args_and_weight
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
event['http']['response']['server-family'] = res_headers['server'].split('/')[0]
if 'accept-encoding' in req_headers:
req_headers['accept-encoding'] = args_and_weight(req_headers['accept-encoding'])
if 'accept-charset' in req_headers:
req_headers['accept-charset'] = args_and_weight(req_headers['accept-charset'])
if 'accept-language' in req_headers:
req_headers['accept-language'] = args_and_weight(req_headers['accept-language'])
if 'accept' in req_headers:
req_headers['accept'] = args_and_weight(req_headers['accept'])
if 'content-length' in req_headers:
req_headers['content-length'] = int(req_headers['content-length'])
if 'content-length' in res_headers:
try:
res_headers['content-length'] = int(res_headers['content-length'])
except ValueError as e:
print "content length is rotten:", e
if 'cookie' in req_headers:
cookie = SimpleCookie()
try:
cookie.load(req_headers['cookie'])
event['http']['request']['cookie'] = dict([(k, cookie[k].value) for k in cookie.keys()])
except CookieError as e:
print "oups' cookie: ", e
event['http']['request']['headers'] = req_headers
event['http']['response']['headers'] = res_headers
logstash.sendall(json.dumps(event, separators=(',', ':')) + "\n")
except socket.error as e:
print "Oups", e
logstash = None
示例15: PloneProxy
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import keys [as 别名]
login_url = 'http://internal.host.name/Plone/login_form'
headers = {}
headers['Content-type'] = 'application/x-www-form-urlencoded'
headers['User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers['Leocornus-Header'] = 'Leocornus Django PloneProxy (httplib2)'
login_form = {}
login_form['__ac_name'] = 'username'
login_form['__ac_password'] = 'password'
login_form['cookies_enabled'] = '1'
login_form['js_enabled'] = '0'
login_form['form.submitted'] = '1'
response, content = http.request(login_url, 'POST', headers=headers, body=urllib.urlencode(login_form))
print content
print '=============================================='
print response
print '=============================================='
cookie = SimpleCookie()
cookie.load(response['set-cookie'])
for key in cookie.keys():
print key
print '===================='
print cookie.get(key).value
print '=============================================='