本文整理汇总了Python中Cookie.SimpleCookie.output方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleCookie.output方法的具体用法?Python SimpleCookie.output怎么用?Python SimpleCookie.output使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cookie.SimpleCookie
的用法示例。
在下文中一共展示了SimpleCookie.output方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
def set_cookie(self, cookie):
"""
Set a cookie.
The cookie will actually be recorded in the WSGI environ and the
'Set-Cookie' header will be generated with the responses are first
sent.
'cookie' can be one of four things:
* a string: the value is considered a cookie header value, i.e. the
bit that would normally be added after 'Set-Cookie: '.
* (name, value) tuple: a persistent cookie is created.
* (name, None) tuple: the named cookie will be removed.
* cookie instance: e.g. one of the cookie types in Python's Cookie
module.
"""
if isinstance(cookie, str):
pass
elif isinstance(cookie, tuple):
name, value = cookie
cookie = SimpleCookie()
cookie[name] = value or ''
cookie[name]['path'] = self.environ['SCRIPT_NAME'] or '/'
if value is None:
cookie[name]['expires'] = 0
cookie[name]['max-age'] = 0
cookie = cookie.output(header='').strip()
else:
cookie = cookie.output(header='').strip()
self.headers.append(cookie)
示例2: __init__
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
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)
示例3: CookieScraper
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [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()
示例4: set_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
def set_cookie(name, _, value):
cookie = SimpleCookie()
cookie[name] = value
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: set_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
def set_cookie(
self, key, value, max_age=None, expires=None, path='/', domain=None
):
"""
Adds the given cookie to the response, so it will be set on
the user's browser.
"""
cookies = Cookie()
cookies[key] = value
if isinstance(max_age, timedelta):
max_age = max_age.seconds + max_age.days*24*60*60
if max_age is not None and expires is None:
expires = datetime.utcnow() + timedelta(seconds=max_age)
if isinstance(expires, timedelta):
expires = datetime.utcnow() + expires
if isinstance(expires, datetime):
expires = '"'+datetime_utils._serialize_cookie_date(expires)+'"'
for var_name, var_value in [('max-age', max_age), ('path', path),
('domain', domain), ('expires', expires)]:
if var_value is not None:
cookies[key][var_name] = str(var_value)
cookies = cookies.output(header='').lstrip()
if cookies:
self.extra_headers.append(('Set-Cookie', cookies))
示例6: cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
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))
示例7: set_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [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))
示例8: make_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [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))
示例9: TestClient
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
class TestClient(object):
def __init__(self):
self.cookies = SimpleCookie()
def get_request(self, path, method="GET", body=None,
**extra):
env = StubWSGIRequest(path)
env['REQUEST_METHOD'] = method
env['wsgi.input'] = StringIO(body)
env['HTTP_COOKIE'] = self.cookies.output(header='', sep='; ')
env.update(extra)
return Request.from_wsgi(env)
def perform_request(self, request, user):
request.website = test_website
if user is not None:
user = User.from_username(user)
# Note that Cookie needs a bytestring.
request.headers.cookie[str('session')] = user.session_token
response = test_website.handle_safely(request)
if response.headers.cookie:
self.cookies.update(response.headers.cookie)
return response
def post(self, path, data, user=None, content_type=MULTIPART_CONTENT,
**extra):
"""Perform a dummy POST request against the test website.
:param path:
The url to perform the virutal-POST to.
:param data:
A dictionary or list of tuples to be encoded before being POSTed.
:param user:
The user id performing the POST.
Any additional parameters will be sent as headers. NOTE that in Aspen
(request.py make_franken_headers) only headers beginning with ``HTTP``
are included in the request - and those are changed to no longer
include ``HTTP``. There are currently 2 exceptions to this:
``'CONTENT_TYPE'``, ``'CONTENT_LENGTH'`` which are explicitly checked
for.
"""
post_data = data
if content_type is MULTIPART_CONTENT:
post_data = encode_multipart(BOUNDARY, data)
request = self.get_request(path, "POST", post_data,
CONTENT_TYPE=str(content_type),
**extra)
return self.perform_request(request, user)
def get(self, path, user=None, **extra):
request = self.get_request(path, "GET")
return self.perform_request(request, user)
示例10: get
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
def get(self, mode = ''):
if mode == 'login':
if 'allowed' in self.request.cookies and \
self.request.cookies['allowed'].count('_'):
_twitter_id, _login_hash = \
self.request.cookies['allowed'].split('_', 1)
user_info = UserInfo.all().filter('twitter_id =', _twitter_id).get()
if user_info and _sha512(user_info.acc_key) == _login_hash:
self.session = Session()
self.session['twitter_id'] = _twitter_id
return self.redirect('/home')
auth = _oauth_handler()
auth_url = auth.get_authorization_url()
memcache.set(auth.request_token.key,
auth.request_token.secret,
3600)
return self.redirect(auth_url)
elif mode == 'verify':
auth = _oauth_handler()
ver = self.request.get('oauth_verifier')
req_key = self.request.get('oauth_token')
req_sec = memcache.get(req_key)
auth.set_request_token(req_key, req_sec)
acc_token = auth.get_access_token(ver)
api = tweepy.API(auth_handler = auth)
me = api.me()
if not UserInfo.all().filter('twitter_id =', str(me.id)).get():
user_info = UserInfo(twitter_id = str(me.id),
screen_name = me.screen_name,
name = me.name,
image = me.profile_image_url,
acc_key = acc_token.key,
acc_sec = acc_token.secret)
user_info.put()
self.session = Session()
self.session.delete_item('twitter_id')
self.session['twitter_id'] = str(me.id)
c = SimpleCookie()
c['allowed'] = '%d_%s' % (me.id, _sha512(acc_token.key))
c['allowed']['path'] = '/auth'
c['allowed']['expires'] = 86400 * 10
self.response.headers.add_header('Set-Cookie', c.output(header = ''))
return self.redirect('/home')
elif mode == 'logout':
user_info = _login_user(self)
if user_info:
self.session = Session()
self.session.delete_item('twitter_id')
return self.redirect('/')
示例11: logout
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
def logout(_request):
body=get_htmltemplate() % ('<p>Logged out</p>')
res=Response()
c=SimpleCookie()
c['authhash']=''
res.set_header(*c.output().split(': '))
res.set_body(body)
return res
示例12: clearCookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
def clearCookie(self, name):
""" cache the cookie set until response sent.
"""
c = SimpleCookie()
c[name] = ''
c[name]['path'] = '/'
c[name]['expires'] = 0
self.__cached_cookie[name] = c.output(header='')
示例13: writeCookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
def writeCookie(self, name, value, path = '/', days_from_now = 30):
""" cache the cookie set until response sent.
"""
c = SimpleCookie()
c[name] = value
c[name]['path'] = path
c[name]['expires'] = GetCacheExpires(days_from_now)
self.__cached_cookie[name] = c.output(header='')
示例14: confirm
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
def confirm(theform, userdir, thisscript):
"""Confirm a login.
Either from an invite or from a user who has registered."""
from dataenc import pass_dec, pass_enc
from login import encodestring
fail = False
try:
theval, daynumber, timestamp = pass_dec(theform['id'].value)
except:
# FIXME: bare except....
newloginfail()
tempstore = ConfigObj(userdir + 'temp.ini')
if not tempstore.has_key(theval):
newloginfail()
uservals = tempstore[theval]
del tempstore[theval]
username = uservals['username']
if username in tempstore['pending']:
tempstore['pending'].remove(username)
tempstore.write()
#
newconfig = ConfigObj(userdir + 'default.ini')
newpath = userdir + username + '.ini'
if os.path.isfile(newpath):
newloginfail()
newconfig.filename = newpath
# FIXME: should this be '' ?
action = None
for entry in uservals:
if entry == 'action':
action = uservals[entry]
elif entry == 'password':
password = uservals[entry]
newconfig[entry] = pass_enc(password, timestamp=True, daynumber=True)
else:
newconfig[entry] = uservals[entry]
newconfig.write()
#
# next we need to create the cookie header to return it
from Cookie import SimpleCookie
thecookie = SimpleCookie()
thecookie['userid'] = encodestring(newconfig['username'], password)
config = ConfigObj(userdir + 'config.ini')
maxage = newconfig['max-age']
cookiepath = config['cookiepath']
if maxage and int(maxage): # possible cause of error here if the maxage value in a users file isn't an integer !!
thecookie['userid']['max-age'] = int(maxage)
if cookiepath:
thecookie['userid']['path'] = cookiepath
if config['adminmail']:
msg = 'A new user has created a login - "%s".\n\n' % thisscript
for entry in newconfig:
if entry != 'password':
msg += entry + ' : ' + newconfig[entry] + '\n'
# FIXME: should be mailme
sendmailme(config['adminmail'], msg, config['email_subject'],
config['adminmail'], html=False)
return action, newconfig, thecookie.output()
示例15: set_cookie
# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import output [as 别名]
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().split(": ", 1)