def test_cookie_options():
app = Sanic('test_text')
@app.route('/')
def handler(request):
response = text("OK")
response.cookies['test'] = 'at you'
response.cookies['test']['httponly'] = True
response.cookies['test']['expires'] = datetime.now() + timedelta(seconds=10)
return response
request, response = sanic_endpoint_test(app)
response_cookies = SimpleCookie()
response_cookies.load(response.headers.get('Set-Cookie', {}))
assert response_cookies['test'].value == 'at you'
assert response_cookies['test']['httponly'] == True
python类SimpleCookie()的实例源码
janprontooneconnect.py 文件源码
项目:python-tarantool-benchmark-and-bootstrap
作者: valentinmk
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def async_good(request):
"""Good page handler."""
global db
global jinja
data = {
"title": "Top of the best stikers for Telegram",
"active_good": "class=\"active\"",
"active_bad": "",
"top": {}
}
session = await session_handler(request=request)
cookies_for_responce = SimpleCookie()
cookies_for_responce['new'] = session['new']
cookies_for_responce['stickers'] = session['stickers']
data["top"] = await db.get_top(12, 'ITERATOR_LE')
text = jinja.get_template('good.html').render(
title=data["title"],
active_good=data["active_good"],
active_bad=data["active_bad"],
top=data["top"]
)
return request.Response(
text=text,
mime_type='text/html',
cookies=cookies_for_responce)
janprontooneconnect.py 文件源码
项目:python-tarantool-benchmark-and-bootstrap
作者: valentinmk
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def action_bad(request):
"""Bad page handler."""
global db
global jinja
data = {
"title": "Top of bad stikers for Telegram",
"active_good": "",
"active_bad": "class=\"active\"",
"top": {}
}
session = await session_handler(request=request)
cookies_for_responce = SimpleCookie()
cookies_for_responce['new'] = session['new']
cookies_for_responce['stickers'] = session['stickers']
data["top"] = await db.get_top(9, 'ITERATOR_GE')
text = jinja.get_template('good.html').render(
title=data["title"],
active_good=data["active_good"],
active_bad=data["active_bad"],
top=data["top"]
)
return request.Response(
text=text,
mime_type='text/html',
cookies=cookies_for_responce)
def test_load(self):
C = cookies.SimpleCookie()
C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
self.assertEqual(C['Customer']['version'], '1')
self.assertEqual(C['Customer']['path'], '/acme')
self.assertEqual(C.output(['path']),
'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
self.assertEqual(C.js_output(), r"""
<script type="text/javascript">
<!-- begin hiding
document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
// end hiding -->
</script>
""")
self.assertEqual(C.js_output(['path']), r"""
<script type="text/javascript">
<!-- begin hiding
document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
// end hiding -->
</script>
""")
def _load_cookie(self):
"""Loads HTTP Cookie from environ"""
cookie = SimpleCookie(self._environ.get('HTTP_COOKIE'))
vishnu_keys = [key for key in cookie.keys() if key == self._config.cookie_name]
# no session was started yet
if not vishnu_keys:
return
morsel = cookie[vishnu_keys[0]]
morsel_value = morsel.value
if self._config.encrypt_key:
cipher = AESCipher(self._config.encrypt_key)
morsel_value = cipher.decrypt(morsel_value)
received_sid = Session.decode_sid(self._config.secret, morsel_value)
if received_sid:
self._sid = received_sid
else:
logging.warn("found cookie with invalid signature")
def test_cookie_options():
app = Sanic('test_text')
@app.route('/')
def handler(request):
response = text("OK")
response.cookies['test'] = 'at you'
response.cookies['test']['httponly'] = True
response.cookies['test']['expires'] = datetime.now() + timedelta(seconds=10)
return response
request, response = app.test_client.get('/')
response_cookies = SimpleCookie()
response_cookies.load(response.headers.get('Set-Cookie', {}))
assert response_cookies['test'].value == 'at you'
assert response_cookies['test']['httponly'] == True
def test_cookie_deletion():
app = Sanic('test_text')
@app.route('/')
def handler(request):
response = text("OK")
del response.cookies['i_want_to_die']
response.cookies['i_never_existed'] = 'testing'
del response.cookies['i_never_existed']
return response
request, response = app.test_client.get('/')
response_cookies = SimpleCookie()
response_cookies.load(response.headers.get('Set-Cookie', {}))
assert int(response_cookies['i_want_to_die']['max-age']) == 0
with pytest.raises(KeyError):
hold_my_beer = response.cookies['i_never_existed']
def test_load(self):
C = cookies.SimpleCookie()
C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
self.assertEqual(C['Customer']['version'], '1')
self.assertEqual(C['Customer']['path'], '/acme')
self.assertEqual(C.output(['path']),
'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
self.assertEqual(C.js_output(), r"""
<script type="text/javascript">
<!-- begin hiding
document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
// end hiding -->
</script>
""")
self.assertEqual(C.js_output(['path']), r"""
<script type="text/javascript">
<!-- begin hiding
document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
// end hiding -->
</script>
""")
def test_special_attrs(self):
# 'expires'
C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
C['Customer']['expires'] = 0
# can't test exact output, it always depends on current date/time
self.assertTrue(C.output().endswith('GMT'))
# loading 'expires'
C = cookies.SimpleCookie()
C.load('Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT')
self.assertEqual(C['Customer']['expires'],
'Wed, 01 Jan 2010 00:00:00 GMT')
C = cookies.SimpleCookie()
C.load('Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT')
self.assertEqual(C['Customer']['expires'],
'Wed, 01 Jan 98 00:00:00 GMT')
# 'max-age'
C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
C['Customer']['max-age'] = 10
self.assertEqual(C.output(),
'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10')
def test_load(self):
C = cookies.SimpleCookie()
C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
self.assertEqual(C['Customer']['version'], '1')
self.assertEqual(C['Customer']['path'], '/acme')
self.assertEqual(C.output(['path']),
'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
self.assertEqual(C.js_output(), r"""
<script type="text/javascript">
<!-- begin hiding
document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
// end hiding -->
</script>
""")
self.assertEqual(C.js_output(['path']), r"""
<script type="text/javascript">
<!-- begin hiding
document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
// end hiding -->
</script>
""")
def test_special_attrs(self):
# 'expires'
C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
C['Customer']['expires'] = 0
# can't test exact output, it always depends on current date/time
self.assertTrue(C.output().endswith('GMT'))
# loading 'expires'
C = cookies.SimpleCookie()
C.load('Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT')
self.assertEqual(C['Customer']['expires'],
'Wed, 01 Jan 2010 00:00:00 GMT')
C = cookies.SimpleCookie()
C.load('Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT')
self.assertEqual(C['Customer']['expires'],
'Wed, 01 Jan 98 00:00:00 GMT')
# 'max-age'
C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
C['Customer']['max-age'] = 10
self.assertEqual(C.output(),
'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10')
def __init__(self, body, headers,
status_code, status_phrase, cookies=None,
content_type=None, charset=None):
assert is_async_generator(body) or isinstance(body, (str, bytes)), (
'body must be str or bytes or async generator, got: %s' % (
type(body),
)
)
assert isinstance(headers, QueryList), (
'header must be a QueryList object'
)
assert isinstance(status_code, int)
assert isinstance(status_phrase, str)
self.body = body
self.headers = headers
self.status_code = status_code
self.status_phrase = status_phrase
self.content_type = content_type or DEFAULT_CONTENT_TYPE
self.charset = charset or DEFAULT_CHARSET
self.cookies = SimpleCookie(cookies)
def _session_cookie(self,forcenew=False):
cookiestring = "\n".join(self.headers.get_all('Cookie',failobj=[]))
c = cookie()
c.load(cookiestring)
try:
if forcenew or self.sessioncookies[c['session_id'].value]-time() > 3600:
raise ValueError('new cookie needed')
except:
c['session_id']=uuid().hex
for m in c:
if m=='session_id':
self.sessioncookies[c[m].value] = time()
c[m]["httponly"] = True
c[m]["max-age"] = 3600
c[m]["expires"] = self.date_time_string(time()+3600)
self.sessionidmorsel = c[m]
break
def test_cookie(self):
response, content = self.assert_get('/')
cookies_ = cookies.SimpleCookie(response['set-cookie'])
self.assertEqual(cookies_['test-cookie'].value, '1')
self.assertIn('dummy-cookie', cookies_)
response, content = self.assert_get('/', cookies=cookies_)
cookies_ = cookies.SimpleCookie(response['set-cookie'])
self.assertEqual(cookies_['test-cookie'].value, '2')
self.assertIn('dummy-cookie', cookies_)
response, content = self.assert_get('/secure')
cookies_ = cookies.SimpleCookie(response['set-cookie'])
self.assertNotIn('dummy-cookie1', cookies_)
self.assertNotIn('dummy-cookie2', cookies_)
self.assertNotIn('dummy-cookie3', cookies_)
#
response, content = self.assert_get('/clear')
cookies_ = cookies.SimpleCookie(response['set-cookie'])
self.assertIn('dummy-cookie', cookies_)
self.assertEqual(cookies_['dummy-cookie']['expires'], 'Sat, 01 Jan 2000 00:00:01 GMT')
self.assertEqual(cookies_['dummy-cookie'].value, '')
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
def __init__(self, *, status=200, reason=None, headers=None):
self._body = None
self._keep_alive = None
self._chunked = False
self._chunk_size = None
self._compression = False
self._compression_force = False
self._headers = CIMultiDict()
self._cookies = SimpleCookie()
self._req = None
self._resp_impl = None
self._eof_sent = False
self._task = None
if headers is not None:
# TODO: optimize CIMultiDict extending
self._headers.extend(headers)
self._headers.setdefault(hdrs.CONTENT_TYPE, 'application/octet-stream')
self.set_status(status, reason)
def test_load(self):
C = cookies.SimpleCookie()
C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
self.assertEqual(C['Customer']['version'], '1')
self.assertEqual(C['Customer']['path'], '/acme')
self.assertEqual(C.output(['path']),
'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
self.assertEqual(C.js_output(), r"""
<script type="text/javascript">
<!-- begin hiding
document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
// end hiding -->
</script>
""")
self.assertEqual(C.js_output(['path']), r"""
<script type="text/javascript">
<!-- begin hiding
document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
// end hiding -->
</script>
""")
def test_special_attrs(self):
# 'expires'
C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
C['Customer']['expires'] = 0
# can't test exact output, it always depends on current date/time
self.assertTrue(C.output().endswith('GMT'))
# loading 'expires'
C = cookies.SimpleCookie()
C.load('Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT')
self.assertEqual(C['Customer']['expires'],
'Wed, 01 Jan 2010 00:00:00 GMT')
C = cookies.SimpleCookie()
C.load('Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT')
self.assertEqual(C['Customer']['expires'],
'Wed, 01 Jan 98 00:00:00 GMT')
# 'max-age'
C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
C['Customer']['max-age'] = 10
self.assertEqual(C.output(),
'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10')
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
def do_POST(self):
# How long was the post data?
length = int(self.headers.get('Content-length', 0))
# Read and parse the post data
data = self.rfile.read(length).decode()
yourname = parse_qs(data)["yourname"][0]
# Create cookie.
c = cookies.SimpleCookie()
# 1. Set the fields of the cookie.
# Give the cookie a value from the 'yourname' variable,
# a domain (localhost), and a max-age.
# Send a 303 back to the root page, with a cookie!
self.send_response(303) # redirect via GET
self.send_header('Location', '/')
self.send_header('Set-Cookie', c['yourname'].OutputString())
self.end_headers()
def do_POST(self):
# How long was the post data?
length = int(self.headers.get('Content-length', 0))
# Read and parse the post data
data = self.rfile.read(length).decode()
yourname = parse_qs(data)["yourname"][0]
# Create cookie.
c = cookies.SimpleCookie()
c['yourname'] = yourname
c['yourname']['domain'] = 'localhost'
c['yourname']['max-age'] = 60
# Send a 303 back to the root page, with a cookie!
self.send_response(303) # redirect via GET
self.send_header('Location', '/')
self.send_header('Set-Cookie', c['yourname'].OutputString())
self.end_headers()
def format_cookie(cookie):
if not cookie:
return None
try:
fmt_headers = {}
cookies = Cookie.SimpleCookie(cookie)
for key, morsel in six.iteritems(cookies):
if "ccsrftoken" in morsel.key:
morsel.coded_value = morsel.value
fmt_headers["X-CSRFTOKEN"] = morsel.value
break
fmt_headers["Cookie"] = cookies.output(header="").lstrip()
return fmt_headers
except (Cookie.CookieError, KeyError):
LOG.error(_LE("The cookie ccsrftoken cannot be formatted"))
raise Cookie.CookieError
def test_cookie_options():
app = Mach9('test_text')
@app.route('/')
def handler(request):
response = text("OK")
response.cookies['test'] = 'at you'
response.cookies['test']['httponly'] = True
response.cookies['test']['expires'] = datetime.now() + timedelta(seconds=10)
return response
request, response = app.test_client.get('/')
response_cookies = SimpleCookie()
response_cookies.load(response.headers.get('Set-Cookie', {}))
assert response_cookies['test'].value == 'at you'
assert response_cookies['test']['httponly'] == True
def test_cookie_deletion():
app = Mach9('test_text')
@app.route('/')
def handler(request):
response = text("OK")
del response.cookies['i_want_to_die']
response.cookies['i_never_existed'] = 'testing'
del response.cookies['i_never_existed']
return response
request, response = app.test_client.get('/')
response_cookies = SimpleCookie()
response_cookies.load(response.headers.get('Set-Cookie', {}))
assert int(response_cookies['i_want_to_die']['max-age']) == 0
with pytest.raises(KeyError):
hold_my_beer = response.cookies['i_never_existed']
def setCookie(self, cookie):
c = cookies.SimpleCookie()
c.load(cookie)
if 'z_c0' not in c:
raise Exception('Invalid cookie: '
'no authorization (z_c0) in cookie')
if '_xsrf' not in c:
raise Exception('Invalid cookie: no _xsrf in cookie')
self.headers['Cookie'] = cookie.strip()
self.headers['Authorization'] = 'Bearer %s' % c['z_c0'].value
self._xsrf = c['_xsrf'].value
def cookies(self):
""" Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
decoded. Use :meth:`get_cookie` if you expect signed cookies. """
cookies = SimpleCookie(self.environ.get('HTTP_COOKIE', '')).values()
return FormsDict((c.key, c.value) for c in cookies)
def copy(self, cls=None):
""" Returns a copy of self. """
cls = cls or BaseResponse
assert issubclass(cls, BaseResponse)
copy = cls()
copy.status = self.status
copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
if self._cookies:
copy._cookies = SimpleCookie()
copy._cookies.load(self._cookies.output(header=''))
return copy
def set_cookies(self, name, value, ttl=12 * 35 * 24 * 60 * 60, path='/'):
"""
:param ttl: cookie????, ?
:type ttl: int
:type path: str
:type name: str
:type value: str
"""
from http.cookies import SimpleCookie
c = SimpleCookie()
c[name] = value
c[name]["path"] = path
c[name]["expires"] = ttl
self.extra_cookies[name] = c[name].OutputString()
def cookies(self):
""" Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
decoded. Use :meth:`get_cookie` if you expect signed cookies. """
cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')).values()
return FormsDict((c.key, c.value) for c in cookies)
def copy(self, cls=None):
''' Returns a copy of self. '''
cls = cls or BaseResponse
assert issubclass(cls, BaseResponse)
copy = cls()
copy.status = self.status
copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
if self._cookies:
copy._cookies = SimpleCookie()
copy._cookies.load(self._cookies.output(header=''))
return copy