本文整理汇总了Python中Cookie.Morsel方法的典型用法代码示例。如果您正苦于以下问题:Python Cookie.Morsel方法的具体用法?Python Cookie.Morsel怎么用?Python Cookie.Morsel使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cookie
的用法示例。
在下文中一共展示了Cookie.Morsel方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setcookie
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def setcookie(name, value, expires='', domain=None,
secure=False, httponly=False, path=None):
"""Sets a cookie."""
morsel = Cookie.Morsel()
name, value = safestr(name), safestr(value)
morsel.set(name, value, urllib.quote(value))
if expires < 0:
expires = -1000000000
morsel['expires'] = expires
morsel['path'] = path or ctx.homepath+'/'
if domain:
morsel['domain'] = domain
if secure:
morsel['secure'] = secure
value = morsel.OutputString()
if httponly:
value += '; httponly'
header('Set-Cookie', value)
示例2: cookies
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def cookies(self):
"""A dictionary of Cookie.Morsel objects."""
if not hasattr(self, "_cookies"):
self._cookies = Cookie.SimpleCookie()
if "Cookie" in self.headers:
try:
parsed = parse_cookie(self.headers["Cookie"])
except Exception:
pass
else:
for k, v in parsed.items():
try:
self._cookies[k] = v
except Exception:
# SimpleCookie imposes some restrictions on keys;
# parse_cookie does not. Discard any cookies
# with disallowed keys.
pass
return self._cookies
示例3: setcookie
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False):
"""
Add a new cookie
"""
newcookie = Morsel()
newcookie.key = key
newcookie.value = value
newcookie.coded_value = value
if max_age is not None:
newcookie['max-age'] = max_age
if expires is not None:
newcookie['expires'] = expires
if path is not None:
newcookie['path'] = path
if domain is not None:
newcookie['domain'] = domain
if secure:
newcookie['secure'] = secure
if httponly:
newcookie['httponly'] = httponly
self.sent_cookies = [c for c in self.sent_cookies if c.key != key]
self.sent_cookies.append(newcookie)
示例4: destroy
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def destroy(self, sessionid):
"""
Destroy a session
:param sessionid: session ID
:return: a list of Set-Cookie headers to be sent to the client
"""
await call_api(self.apiroutine, 'memorystorage', 'delete', {'key': __name__ + '.' + sessionid})
m = Morsel()
m.key = self.cookiename
m.value = 'deleted'
m.coded_value = 'deleted'
opts = {'path':'/', 'httponly':True, 'max-age':0}
m.update(opts)
return [m]
示例5: setcookie
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def setcookie(name, value, expires='', domain=None,
secure=False, httponly=False, path=None):
"""Sets a cookie."""
morsel = Morsel()
name, value = safestr(name), safestr(value)
morsel.set(name, value, quote(value))
if isinstance(expires, int) and expires < 0:
expires = -1000000000
morsel['expires'] = expires
morsel['path'] = path or ctx.homepath+'/'
if domain:
morsel['domain'] = domain
if secure:
morsel['secure'] = secure
value = morsel.OutputString()
if httponly:
value += '; httponly'
header('Set-Cookie', value)
示例6: start
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def start(self, cookies, cookieopts = None):
"""
Session start operation. First check among the cookies to find existed sessions;
if there is not an existed session, create a new one.
:param cookies: cookie header from the client
:param cookieopts: extra options used when creating a new cookie
:return: ``(session_handle, cookies)`` where session_handle is a SessionHandle object,
and cookies is a list of created Set-Cookie headers (may be empty)
"""
c = SimpleCookie(cookies)
sid = c.get(self.cookiename)
create = True
if sid is not None:
sh = await self.get(sid.value)
if sh is not None:
return (self.SessionHandle(sh, self.apiroutine), [])
if create:
sh = await self.create()
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)
return (sh, [m])
示例7: __init__
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def __init__(self, conpool=None, cookie_str=None, throw_exception=True,user_agent = None,headers=None):
"""conpool: 创建的连接池最大数量,类型为 int,默认为 10
cookie_str: 用户自己定义的 Cookie,类型为 String
throw_exception: 是否抛出遇到的异常,类型为 bool,默认为 True
为了全局配置useragent header 这里加入相关选项
"""
self.throw_exception = throw_exception
if conpool is None:
self.conpool = httpconpool(10)
else:
self.conpool = conpool
Cookie.Morsel = MorselHook
self.initcookie = Cookie.SimpleCookie()
if cookie_str:
if not cookie_str.endswith(';'):
cookie_str += ";"
for cookiepart in cookie_str.split(";"):
if cookiepart.strip() != "":
cookiekey, cookievalue = cookiepart.split("=", 1)
self.initcookie[cookiekey.strip()] = cookievalue.strip()
self.cookiepool = {}
self.user_agent = user_agent
self.headers = headers
示例8: set_cookie
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
# The cookie library only accepts type str, in both python 2 and 3
name = escape.native_str(name)
value = escape.native_str(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookie"):
self._new_cookie = Cookie.SimpleCookie()
if name in self._new_cookie:
del self._new_cookie[name]
self._new_cookie[name] = value
morsel = self._new_cookie[name]
if domain:
morsel["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(
days=expires_days)
if expires:
timestamp = calendar.timegm(expires.utctimetuple())
morsel["expires"] = email.utils.formatdate(
timestamp, localtime=False, usegmt=True)
if path:
morsel["path"] = path
for k, v in kwargs.iteritems():
if k == 'max_age':
k = 'max-age'
morsel[k] = v
示例9: cookies
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def cookies(self):
"""A dictionary of Cookie.Morsel objects."""
if not hasattr(self, "_cookies"):
self._cookies = Cookie.SimpleCookie()
if "Cookie" in self.headers:
try:
self._cookies.load(
native_str(self.headers["Cookie"]))
except Exception:
self._cookies = {}
return self._cookies
示例10: cookies
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def cookies(self):
"""A dictionary of Cookie.Morsel objects."""
if not hasattr(self, "_cookies"):
self._cookies = Cookie.SimpleCookie()
if "Cookie" in self.headers:
try:
self._cookies.load(
native_str(self.headers["Cookie"]))
except Exception:
self._cookies = None
return self._cookies
示例11: cookies
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def cookies(self):
"""A dictionary of Cookie.Morsel objects."""
if not hasattr(self, "_cookies"):
self._cookies = Cookie.BaseCookie()
if "Cookie" in self.request.headers:
try:
self._cookies.load(self.request.headers["Cookie"])
except:
self.clear_all_cookies()
return self._cookies
示例12: set_cookie
# 需要导入模块: import Cookie [as 别名]
# 或者: from Cookie import Morsel [as 别名]
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
name = _utf8(name)
value = _utf8(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookies"):
self._new_cookies = []
new_cookie = Cookie.BaseCookie()
self._new_cookies.append(new_cookie)
new_cookie[name] = value
if domain:
new_cookie[name]["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(
days=expires_days)
if expires:
timestamp = calendar.timegm(expires.utctimetuple())
new_cookie[name]["expires"] = email.utils.formatdate(
timestamp, localtime=False, usegmt=True)
if path:
new_cookie[name]["path"] = path
for k, v in kwargs.iteritems():
new_cookie[name][k] = v