本文整理汇总了Python中werkzeug.http.dump_cookie函数的典型用法代码示例。如果您正苦于以下问题:Python dump_cookie函数的具体用法?Python dump_cookie怎么用?Python dump_cookie使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dump_cookie函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_cookies
def test_cookies(self):
strict_eq(
dict(
http.parse_cookie(
"dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd"
'c762809248d4beed; a=42; b="\\";"'
)
),
{
"CP": u"null*",
"PHPSESSID": u"0a539d42abc001cdc762809248d4beed",
"a": u"42",
"dismiss-top": u"6",
"b": u'";',
},
)
rv = http.dump_cookie(
"foo", "bar baz blub", 360, httponly=True, sync_expires=False
)
assert type(rv) is str
assert set(rv.split("; ")) == {
"HttpOnly",
"Max-Age=360",
"Path=/",
'foo="bar baz blub"',
}
strict_eq(
dict(http.parse_cookie("fo234{=bar; blub=Blah")),
{"fo234{": u"bar", "blub": u"Blah"},
)
strict_eq(http.dump_cookie("key", "xxx/"), "key=xxx/; Path=/")
strict_eq(http.dump_cookie("key", "xxx="), "key=xxx=; Path=/")
示例2: test_cookie_domain_encoding
def test_cookie_domain_encoding(self):
val = http.dump_cookie("foo", "bar", domain=u"\N{SNOWMAN}.com")
strict_eq(val, "foo=bar; Domain=xn--n3h.com; Path=/")
val = http.dump_cookie("foo", "bar", domain=u".\N{SNOWMAN}.com")
strict_eq(val, "foo=bar; Domain=.xn--n3h.com; Path=/")
val = http.dump_cookie("foo", "bar", domain=u".foo.com")
strict_eq(val, "foo=bar; Domain=.foo.com; Path=/")
示例3: test_cookie_domain_encoding
def test_cookie_domain_encoding(self):
val = http.dump_cookie('foo', 'bar', domain=u'\N{SNOWMAN}.com')
self.assert_strict_equal(val, 'foo=bar; Domain=xn--n3h.com; Path=/')
val = http.dump_cookie('foo', 'bar', domain=u'.\N{SNOWMAN}.com')
self.assert_strict_equal(val, 'foo=bar; Domain=.xn--n3h.com; Path=/')
val = http.dump_cookie('foo', 'bar', domain=u'.foo.com')
self.assert_strict_equal(val, 'foo=bar; Domain=.foo.com; Path=/')
示例4: test_cookie_maxsize
def test_cookie_maxsize(self, recwarn):
val = http.dump_cookie('foo', 'bar' * 1360 + 'b')
assert len(recwarn) == 0
assert len(val) == 4093
http.dump_cookie('foo', 'bar' * 1360 + 'ba')
assert len(recwarn) == 1
w = recwarn.pop()
assert 'cookie is too large' in str(w.message)
http.dump_cookie('foo', b'w' * 502, max_size=512)
assert len(recwarn) == 1
w = recwarn.pop()
assert 'the limit is 512 bytes' in str(w.message)
示例5: post_process
def post_process(self, environ, headers):
user = User.get_current()
if not user:
cookies = http.parse_cookie(environ)
if self.name in cookies:
raw = http.dump_cookie(self.name, '', expires=1)
headers.append((utils.to_native('Set-Cookie'), raw))
return
cookie = SecureCookie({
'uid': user.id,
'session_token': user.get_session_token(),
}, self.secret)
raw = http.dump_cookie(self.name, cookie.serialize(),
expires=self.expires, max_age=self.max_age)
headers.append((utils.to_native('Set-Cookie'), raw))
示例6: injecting_start_response
def injecting_start_response(status, headers, exc_info=None):
# Iterate through the headers looking for Set-Cookie
updates = False
for idx, (header, value) in enumerate(headers):
if header == 'Set-Cookie':
cookie = parse_cookie(value)
if 'zappa' in cookie:
# We found a header in the response object that sets
# zappa as a cookie. Delete it.
del(headers[idx])
del(cookie['zappa'])
print 'deleted zappa set-cooke header'
print 'remaining cookie', cookie
if cookie:
updates = True
request_cookies.update(cookie)
print 'setting cookie', cookie
# Encode cookies into Zappa cookie
if updates and request_cookies:
final_cookies = ["{cookie}={value}".format(cookie=k, value=v) for k, v in request_cookies.items()]
encoded = base58.b58encode(';'.join(final_cookies))
headers.append(('Set-Cookie', dump_cookie('zappa', value=encoded)))
return start_response(status, headers, exc_info)
示例7: set_cookie
def set_cookie(self, name, value='', max_age=None,
path='/', domain=None, secure=False, httponly=True):
"""Add a cookie to the response.
:param name: Name of the cookie.
:param value: Value of the cookie (should always be a string).
:param max_age: Maximum age (leave `None` for "browser session").
:param path: Path to bind the cookie to [default `'/'`].
:param domain: Domain to bind the cookie to [default `None`].
:param secure: Secure the cookie [default `False`],
handy: `request.ssl`.
:param httponly: Cookie not accessable by JavaScript [default `true`].
:type name: str
:type value: str
:type max_age: int | None
:type path: str
:type domain: str | None
:type secure: bool
:type httponly: bool
"""
self.headers.add('Set-Cookie', dump_cookie(
name, value=str(value), max_age=max_age,
path=path, domain=domain,
secure=secure, httponly=httponly,
charset='utf-8', sync_expires=True))
示例8: _construct_cookie
def _construct_cookie(self, session, unset=False):
params = self.configuration['cookie']
expires = (LONG_AGO if unset else params.get('expires'))
return dump_cookie(params['name'], session.sid, params.get('max_age'),
expires, params.get('path', '/'), params.get('domain'),
params.get('secure'), params.get('httponly', True))
示例9: test_cookie_quoting
def test_cookie_quoting(self):
val = http.dump_cookie("foo", "?foo")
self.assert_strict_equal(val, 'foo="?foo"; Path=/')
self.assert_strict_equal(dict(http.parse_cookie(val)), {'foo': u'?foo'})
self.assert_strict_equal(dict(http.parse_cookie(r'foo="foo\054bar"')),
{'foo': u'foo,bar'})
示例10: test_cookie_unicode_dumping
def test_cookie_unicode_dumping(self):
val = http.dump_cookie('foo', u'\N{SNOWMAN}')
h = datastructures.Headers()
h.add('Set-Cookie', val)
self.assert_equal(h['Set-Cookie'], 'foo="\\342\\230\\203"; Path=/')
cookies = http.parse_cookie(h['Set-Cookie'])
self.assert_equal(cookies['foo'], u'\N{SNOWMAN}')
示例11: session_start_response
def session_start_response(status, headers, exc_info=None):
if session.should_save or session == {}:
# add our cookie to headers
c = dump_cookie(self.cookie_name,
value=environ[self.wsgi_name].serialize(),
max_age=datetime.timedelta(days=self.expire_days))
headers.append(('Set-Cookie', c))
return start_response(status, headers, exc_info=exc_info)
示例12: test_cookie_unicode_dumping
def test_cookie_unicode_dumping(self):
val = http.dump_cookie("foo", u"\N{SNOWMAN}")
h = datastructures.Headers()
h.add("Set-Cookie", val)
assert h["Set-Cookie"] == 'foo="\\342\\230\\203"; Path=/'
cookies = http.parse_cookie(h["Set-Cookie"])
assert cookies["foo"] == u"\N{SNOWMAN}"
示例13: encode_response
def encode_response(self, status, headers, exc_info=None):
"""
Zappa-ify our application response!
This means:
- Updating any existing cookies.
- Packing all our cookies into a single ZappaCookie.
- Injecting redirect HTML if setting a Cookie on a redirect.
"""
# All the non-cookie headers should be sent unharmed.
new_headers = [(header[0], header[1]) for header in headers if header[0] != 'Set-Cookie']
# Filter the headers for Set-Cookie header
cookie_dicts = [
{header[1].split('=', 1)[0].strip():header[1].split('=', 1)[1]}
for header
in headers
if header[0] == 'Set-Cookie'
]
# Update request_cookies with cookies from the response. If there are
# multiple occuring cookies, the last one present in the headers wins.
map(self.request_cookies.update, cookie_dicts)
# Get the oldest expire time, and set the Zappa cookie age to that.
# Else, let this be a session cookie.
expires = None
for _, exp in self.iter_cookies_expires():
if exp > expires:
expires = exp
# JSON-ify the cookie and encode it.
pack_s = json.dumps(self.request_cookies)
encoded = base58.b58encode(pack_s)
# Set the result as the zappa cookie
new_headers.append(
(
'Set-Cookie',
dump_cookie('zappa', value=encoded, expires=expires)
)
)
# If setting cookie on a 301/2,
# return 200 and replace the content with a javascript redirector
# content_type_header_key = [k for k, v in enumerate(new_headers) if v[0] == 'Content-Type']
# if len(content_type_header_key) > 0:
# if "text/html" in new_headers[content_type_header_key[0]][1]:
# if status != '200 OK':
# for key, value in new_headers:
# if key != 'Location':
# continue
# self.redirect_content = REDIRECT_HTML.replace('REDIRECT_ME', value)
# status = '200 OK'
# break
return self.start_response(status, new_headers, exc_info)
示例14: test_cookie_script
def test_cookie_script(self):
""""""
url = '/test-cookie'
cookie = dump_cookie('test-cookie', '<script>alert("ho")</script>')
with self.app.test_request_context(url, method='GET',
headers={'Cookie': cookie}):
response = self.app.dispatch_request()
self.assertNotIn('<script>', response.data)
示例15: wrapper
def wrapper(request):
request.cookies = _parse_cookie(request.headers.get('Cookie', 'No Cookie'))
response = func(request)
if hasattr(response, 'cookies'):
cookies_strings = []
for key, value in response.cookies.items():
cookies_strings.append(dump_cookie(key, **value))
response.headers['Set-Cookie'] = ",".join(cookies_strings)
return response