本文整理汇总了Python中http.cookies.Morsel方法的典型用法代码示例。如果您正苦于以下问题:Python cookies.Morsel方法的具体用法?Python cookies.Morsel怎么用?Python cookies.Morsel使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.cookies
的用法示例。
在下文中一共展示了cookies.Morsel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cookies
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies 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
示例2: setcookie
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies 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)
示例3: destroy
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies 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]
示例4: setcookie
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies 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)
示例5: toCookieParam
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def toCookieParam (m):
"""
Convert Python’s http.cookies.Morsel to Chrome’s CookieParam, see
https://chromedevtools.github.io/devtools-protocol/1-3/Network#type-CookieParam
"""
assert isinstance (m, Morsel)
out = {'name': m.key, 'value': m.value}
# unsupported by chrome
for k in ('max-age', 'comment', 'version'):
if m[k]:
raise ValueError (f'Unsupported cookie attribute {k} set, cannot convert')
for mname, cname in [('expires', None), ('path', None), ('domain', None), ('secure', None), ('httponly', 'httpOnly')]:
value = m[mname]
if value:
cname = cname or mname
out[cname] = value
return out
示例6: test_setdefault
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def test_setdefault(self):
morsel = cookies.Morsel()
morsel.update({
'domain': 'example.com',
'version': 2,
})
# this shouldn't override the default value
self.assertEqual(morsel.setdefault('expires', 'value'), '')
self.assertEqual(morsel['expires'], '')
self.assertEqual(morsel.setdefault('Version', 1), 2)
self.assertEqual(morsel['version'], 2)
self.assertEqual(morsel.setdefault('DOMAIN', 'value'), 'example.com')
self.assertEqual(morsel['domain'], 'example.com')
with self.assertRaises(cookies.CookieError):
morsel.setdefault('invalid', 'value')
self.assertNotIn('invalid', morsel)
示例7: update_cookies
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def update_cookies(self, cookies: Optional[LooseCookies]) -> None:
"""Update request cookies header."""
if not cookies:
return
c = SimpleCookie()
if hdrs.COOKIE in self.headers:
c.load(self.headers.get(hdrs.COOKIE, ''))
del self.headers[hdrs.COOKIE]
if isinstance(cookies, Mapping):
iter_cookies = cookies.items()
else:
iter_cookies = cookies # type: ignore
for name, value in iter_cookies:
if isinstance(value, Morsel):
# Preserve coded_value
mrsl_val = value.get(value.key, Morsel())
mrsl_val.set(value.key, value.value, value.coded_value) # type: ignore # noqa
c[name] = mrsl_val
else:
c[name] = value # type: ignore
self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip()
示例8: update_cookies
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def update_cookies(self, cookies):
"""Update request cookies header."""
if not cookies:
return
c = SimpleCookie()
if hdrs.COOKIE in self.headers:
c.load(self.headers.get(hdrs.COOKIE, ''))
del self.headers[hdrs.COOKIE]
for name, value in cookies.items():
if isinstance(value, Morsel):
# Preserve coded_value
mrsl_val = value.get(value.key, Morsel())
mrsl_val.set(value.key, value.value, value.coded_value)
c[name] = mrsl_val
else:
c[name] = value
self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip()
示例9: cookies
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def cookies(self) -> Dict[str, http.cookies.Morsel]:
"""An alias for
`self.request.cookies <.httputil.HTTPServerRequest.cookies>`."""
return self.request.cookies
示例10: __setitem__
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def __setitem__(self, key, value):
if isinstance(value, Morsel):
# allow assignment of constructed Morsels (e.g. for pickling)
dict.__setitem__(self, key, value)
else:
super().__setitem__(key, value)
示例11: start
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies 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])
示例12: test_set_cookies
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def test_set_cookies (tab, recordingServer):
""" Make sure cookies are set properly and only affect the domain they were
set for """
logger = Logger ()
url, reqs = recordingServer
cookies = []
c = Morsel ()
c.set ('foo', 'bar', '')
c['domain'] = 'localhost'
cookies.append (c)
c = Morsel ()
c.set ('buz', 'beef', '')
c['domain'] = 'nonexistent.example'
settings = ControllerSettings (idleTimeout=1, timeout=60, cookies=cookies)
controller = SinglePageController (url=url, logger=logger,
service=Process (), behavior=[], settings=settings)
await asyncio.wait_for (controller.run (), settings.timeout*2)
assert len (reqs) == 1
req = reqs[0]
reqCookies = SimpleCookie (req.headers['cookie'])
assert len (reqCookies) == 1
c = next (iter (reqCookies.values ()))
assert c.key == cookies[0].key
assert c.value == cookies[0].value
示例13: test_defaults
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def test_defaults(self):
morsel = cookies.Morsel()
self.assertIsNone(morsel.key)
self.assertIsNone(morsel.value)
self.assertIsNone(morsel.coded_value)
self.assertEqual(morsel.keys(), cookies.Morsel._reserved.keys())
for key, val in morsel.items():
self.assertEqual(val, '', key)
示例14: test_reserved_keys
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def test_reserved_keys(self):
M = cookies.Morsel()
# tests valid and invalid reserved keys for Morsels
for i in M._reserved:
# Test that all valid keys are reported as reserved and set them
self.assertTrue(M.isReservedKey(i))
M[i] = '%s_value' % i
for i in M._reserved:
# Test that valid key values come out fine
self.assertEqual(M[i], '%s_value' % i)
for i in "the holy hand grenade".split():
# Test that invalid keys raise CookieError
self.assertRaises(cookies.CookieError,
M.__setitem__, i, '%s_value' % i)
示例15: test_setter
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def test_setter(self):
M = cookies.Morsel()
# tests the .set method to set keys and their values
for i in M._reserved:
# Makes sure that all reserved keys can't be set this way
self.assertRaises(cookies.CookieError,
M.set, i, '%s_value' % i, '%s_value' % i)
for i in "thou cast _the- !holy! ^hand| +*grenade~".split():
# Try typical use case. Setting decent values.
# Check output and js_output.
M['path'] = '/foo' # Try a reserved key as well
M.set(i, "%s_val" % i, "%s_coded_val" % i)
self.assertEqual(
M.output(),
"Set-Cookie: %s=%s; Path=/foo" % (i, "%s_coded_val" % i))
expected_js_output = """
<script type="text/javascript">
<!-- begin hiding
document.cookie = "%s=%s; Path=/foo";
// end hiding -->
</script>
""" % (i, "%s_coded_val" % i)
self.assertEqual(M.js_output(), expected_js_output)
for i in ["foo bar", "foo@bar"]:
# Try some illegal characters
self.assertRaises(cookies.CookieError,
M.set, i, '%s_value' % i, '%s_value' % i)