本文整理汇总了Python中http.cookies.SimpleCookie方法的典型用法代码示例。如果您正苦于以下问题:Python cookies.SimpleCookie方法的具体用法?Python cookies.SimpleCookie怎么用?Python cookies.SimpleCookie使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.cookies
的用法示例。
在下文中一共展示了cookies.SimpleCookie方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_secure_cookie_session_interface_save_session
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def test_secure_cookie_session_interface_save_session() -> None:
session = SecureCookieSession()
session["something"] = "else"
interface = SecureCookieSessionInterface()
app = Quart(__name__)
app.secret_key = "secret"
response = Response("")
await interface.save_session(app, session, response)
cookies: SimpleCookie = SimpleCookie()
cookies.load(response.headers["Set-Cookie"])
cookie = cookies[app.session_cookie_name]
assert cookie["path"] == interface.get_cookie_path(app)
assert cookie["httponly"] == "" if not interface.get_cookie_httponly(app) else True
assert cookie["secure"] == "" if not interface.get_cookie_secure(app) else True
if version_info >= (3, 8):
assert cookie["samesite"] == (interface.get_cookie_samesite(app) or "")
assert cookie["domain"] == (interface.get_cookie_domain(app) or "")
assert cookie["expires"] == (interface.get_expiration_time(app, session) or "")
assert response.headers["Vary"] == "Cookie"
示例2: test_cookies_asgi
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def test_cookies_asgi(app):
@app.route("/")
def handler(request):
cookie_value = request.cookies["test"]
response = text(f"Cookies are: {cookie_value}")
response.cookies["right_back"] = "at you"
return response
request, response = await app.asgi_client.get(
"/", cookies={"test": "working!"}
)
response_cookies = SimpleCookie()
response_cookies.load(response.headers.get("set-cookie", {}))
assert response.text == "Cookies are: working!"
assert response_cookies["right_back"].value == "at you"
示例3: test_cookie_options
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def test_cookie_options(app):
@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"] is True
示例4: test_cookie_deletion
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def test_cookie_deletion(app):
@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):
response.cookies["i_never_existed"]
示例5: test_statistics_lazy_cookies
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def test_statistics_lazy_cookies(client, site):
tag_instant_statistics()
tag_lazy_statistics()
client.cookies = SimpleCookie({"wtm": ""})
response = client.post(
"/wtm/lazy/", json.dumps({}), content_type="application/json"
)
data = response.json()
assert response.status_code == 200
assert "tags" in data
assert len(data["tags"]) == 0
assert "wtm" in response.cookies
consent_state = get_consent(response)
assert consent_state.get("statistics", "") == "true"
示例6: test_view_necessary
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def test_view_necessary(client, site):
response = client.get(site.root_page.url)
assert response.status_code == 200
tag_instant_necessary(tag_location=Tag.TOP_HEAD)
client.cookies = SimpleCookie({"wtm": "necessary:true"})
response = client.get(site.root_page.url)
assert response.status_code == 200
assert b'console.log("necessary instant")' in response.content
tag_instant_necessary(name="instant necessary 2", tag_location=Tag.BOTTOM_HEAD)
client.cookies = SimpleCookie({"wtm": "necessary:true"})
response = client.get(site.root_page.url)
assert response.status_code == 200
assert b'console.log("necessary instant")' in response.content
client.cookies = SimpleCookie({"wtm": "necessary:false"})
response = client.get(site.root_page.url)
assert response.status_code == 200
assert b'console.log("necessary instant")' in response.content
示例7: _frodotk_referer_patch
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def _frodotk_referer_patch(self):
response = self.fetch_url_content('https://m.douban.com/mine/')
if not response:
raise Exception('服务器无法访问,请稍后重试')
set_cookie = response.headers['Set-Cookie']
set_cookie = set_cookie.replace(',', ';')
cookie = cookies.SimpleCookie()
cookie.load(set_cookie)
try:
patched_cookie = self._account.session + '; frodotk="{0}"'.format(cookie['frodotk'].value)
except KeyError:
raise Exception('服务器没有正确授予Cookie,可能是登录会话过期,请重新登录')
self._request_session.headers.update({
'Cookie': patched_cookie,
'Referer': 'https://m.douban.com/',
})
示例8: cookies
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [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
示例9: request
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def request(self, **kwargs):
# create user
username = 'substra'
password = 'p@$swr0d44'
user, created = User.objects.get_or_create(username=username)
if created:
user.set_password(password)
user.save()
# simulate login
serializer = CustomTokenObtainPairSerializer(data={
'username': username,
'password': password
})
serializer.is_valid()
data = serializer.validated_data
access_token = str(data.access_token)
# simulate right httpOnly cookie and Authorization jwt
jwt_auth_header = generate_jwt_auth_header('.'.join(access_token.split('.')[0:2]))
self.credentials(HTTP_AUTHORIZATION=jwt_auth_header)
self.cookies = SimpleCookie({'signature': access_token.split('.')[2]})
return super().request(**kwargs)
示例10: test_auth_callback_calls_github_apis_and_sets_cookie
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def test_auth_callback_calls_github_apis_and_sets_cookie(
redirect_path, require_auth_app
):
cookie = SimpleCookie()
cookie["asgi_auth_redirect"] = redirect_path
cookie["asgi_auth_redirect"]["path"] = "/"
instance = ApplicationCommunicator(
require_auth_app,
{
"type": "http",
"http_version": "1.0",
"method": "GET",
"path": "/-/auth-callback",
"query_string": b"code=github-code-here",
"headers": [[b"cookie", cookie.output(header="").lstrip().encode("utf8")]],
},
)
await instance.send_input({"type": "http.request"})
output = await instance.receive_output(1)
assert_redirects_and_sets_cookie(require_auth_app, output, redirect_path)
示例11: signed_auth_cookie_header
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def signed_auth_cookie_header(app, ts=None):
signer = Signer(app.cookie_secret)
cookie = SimpleCookie()
cookie["asgi_auth"] = signer.sign(
json.dumps(
{
"id": "123",
"name": "GitHub User",
"username": "demouser",
"email": "demouser@example.com",
"ts": ts or int(time.time()),
},
separators=(",", ":"),
)
)
cookie["asgi_auth"]["path"] = "/"
return cookie.output(header="").lstrip().encode("utf8")
示例12: test_load
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
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>
""")
示例13: test_special_attrs
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
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')
示例14: __init__
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def __init__(self):
self.status = None
self.header_list = None
self._body = []
self.time = time.time()
self.headers = httputil.HeaderMap()
# Since we know all our keys are titled strings, we can
# bypass HeaderMap.update and get a big speed boost.
dict.update(self.headers, {
'Content-Type': 'text/html',
'Server': 'CherryPy/' + cherrypy.__version__,
'Date': httputil.HTTPDate(self.time),
})
self.cookie = SimpleCookie()
示例15: test_session_expiration_set_to_configured_lifetime
# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import SimpleCookie [as 别名]
def test_session_expiration_set_to_configured_lifetime(self, time_mock, utc_time_sans_frac_mock):
timestamp = time.mktime(datetime(2017, 1, 1).timetuple())
time_mock.return_value = timestamp
utc_time_sans_frac_mock.return_value = int(timestamp)
exp_time = 10
state = 'test_state'
nonce = 'test_nonce'
id_token = IdToken(iss=self.PROVIDER_BASEURL,
aud=self.CLIENT_ID,
sub='sub1',
exp=int(timestamp) + exp_time,
iat=int(timestamp),
nonce=nonce)
token_response = {'access_token': 'test', 'token_type': 'Bearer', 'id_token': id_token.to_jwt()}
token_endpoint = self.PROVIDER_BASEURL + '/token'
responses.add(responses.POST, token_endpoint, json=token_response)
session_lifetime = 1234
self.app.config['PERMANENT_SESSION_LIFETIME'] = session_lifetime
self.init_app(provider_metadata_extras={'token_endpoint': token_endpoint})
with self.app.test_client() as client:
with client.session_transaction() as session:
UserSession(session, self.PROVIDER_NAME)
session['destination'] = '/'
session['state'] = state
session['nonce'] = nonce
resp = client.get('/redirect_uri?state={}&code=test'.format(state))
cookies = SimpleCookie()
cookies.load(resp.headers['Set-Cookie'])
session_cookie_expiration = cookies[self.app.config['SESSION_COOKIE_NAME']]['expires']
parsed_expiration = datetime.strptime(session_cookie_expiration, '%a, %d-%b-%Y %H:%M:%S GMT')
cookie_lifetime = (parsed_expiration - datetime.utcnow()).total_seconds()
assert cookie_lifetime == pytest.approx(session_lifetime, abs=1)