本文整理汇总了Python中http.cookies方法的典型用法代码示例。如果您正苦于以下问题:Python http.cookies方法的具体用法?Python http.cookies怎么用?Python http.cookies使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http
的用法示例。
在下文中一共展示了http.cookies方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: apply
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def apply(self, url, headers):
"""Adds cookies to provided ``headers``. If ``headers`` already
contains any cookies, they would be merged with instance ones.
:param str url: Request URL
:param dict headers: Request headers
"""
if self._cookies is None:
return
cookie = http.cookies.SimpleCookie()
if COOKIE in headers:
cookie.load(headers.get(COOKIE, ''))
del headers[COOKIE]
for name, value in self._cookies.items():
if isinstance(value, http.cookies.Morsel):
# use dict method because SimpleCookie class modifies value
dict.__setitem__(cookie, name, value)
else:
cookie[name] = value
headers[COOKIE] = cookie.output(header='', sep=';').strip()
示例2: cookies
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def cookies(self) -> Dict[str, http.cookies.Morsel]:
"""A dictionary of ``http.cookies.Morsel`` objects."""
if not hasattr(self, "_cookies"):
self._cookies = http.cookies.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: delete_param
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def delete_param(self, para_type, para_name):
"""
删除HTTP请求的某个变量,支持get、post、Cookie、headers
Parameters:
para_type - str, 要删除的参数类型,可选get、post、Cookie、headers
para_name - str, 要删除的参数名
Raises:
exceptions.DataParamError - 参数错误引发此异常
"""
if para_type == "cookies" and para_name in self.http_data["cookies"]:
del self.http_data["cookies"][para_name]
elif para_type == "get" and para_name in self.http_data["params"]:
del self.http_data["params"][para_name]
elif para_type == "post" and para_name in self.http_data["data"]:
del self.http_data["data"][para_name]
elif para_type == "headers" and para_name in self.http_data["headers"]:
del self.http_data["headers"][para_name]
else:
Logger().error("Use an invalid para_type in set_param method!")
raise exceptions.DataParamError
示例4: get_aiohttp_param
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def get_aiohttp_param(self):
"""
获取调用aiphttp发送http请求相关方法所需的参数
Returns:
dict, 字典形式的参数
"""
result = {
"url": self.http_data["url"],
"headers": self.http_data["headers"],
"params": self.http_data["params"],
"cookies": self.http_data["cookies"]
}
if self.content_type.startswith("application/json"):
result["json"] = self.http_data["json"]
elif self.content_type.startswith("multipart/form-data"):
result["data"] = self._make_multipart()
if self.http_data["headers"].get("content-type", None) is not None:
del result["headers"]["content-type"]
elif self.http_data["body"] is not None:
result["data"] = self.http_data["body"]
else:
result["data"] = self.http_data["data"]
return result
示例5: test_no_httponly_session_cookie
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def test_no_httponly_session_cookie(self):
request = RequestFactory().get('/')
response = HttpResponse('Session test')
middleware = SessionMiddleware()
# Simulate a request the modifies the session
middleware.process_request(request)
request.session['hello'] = 'world'
# Handle the response through the middleware
response = middleware.process_response(request, response)
self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], '')
self.assertNotIn(
cookies.Morsel._reserved['httponly'],
str(response.cookies[settings.SESSION_COOKIE_NAME])
)
示例6: test_session_delete_on_end
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def test_session_delete_on_end(self):
request = RequestFactory().get('/')
response = HttpResponse('Session test')
middleware = SessionMiddleware()
# Before deleting, there has to be an existing cookie
request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'
# Simulate a request that ends the session
middleware.process_request(request)
request.session.flush()
# Handle the response through the middleware
response = middleware.process_response(request, response)
# The cookie was deleted, not recreated.
# A deleted cookie header looks like:
# Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
self.assertEqual(
'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; '
'Max-Age=0; Path=/'.format(
settings.SESSION_COOKIE_NAME,
),
str(response.cookies[settings.SESSION_COOKIE_NAME])
)
示例7: test_flush_empty_without_session_cookie_doesnt_set_cookie
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def test_flush_empty_without_session_cookie_doesnt_set_cookie(self):
request = RequestFactory().get('/')
response = HttpResponse('Session test')
middleware = SessionMiddleware()
# Simulate a request that ends the session
middleware.process_request(request)
request.session.flush()
# Handle the response through the middleware
response = middleware.process_response(request, response)
# A cookie should not be set.
self.assertEqual(response.cookies, {})
# The session is accessed so "Vary: Cookie" should be set.
self.assertEqual(response['Vary'], 'Cookie')
示例8: update
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def update(self, response):
"""Updates cookies from the response.
:param response: :class:`aiocouchdb.client.HttpResponse` instance
"""
if response.cookies:
self._cookies = response.cookies
示例9: testAdd
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def testAdd(self):
cookie_jar = SimpleCookieJar()
cookie_jar.add("")
self.assertFalse(cookie_jar.jar, "Cookie with no domain should not be added to the jar")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b")
self.assertFalse(cookie_jar.jar, "Cookie with no domain should not be added to the jar")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; domain=.abc")
self.assertTrue(".abc" in cookie_jar.jar)
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; domain=abc")
self.assertTrue(".abc" in cookie_jar.jar)
self.assertTrue("abc" not in cookie_jar.jar)
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; c=d; domain=abc")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; c=d; domain=abc")
cookie_jar.add("e=f; domain=abc")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d; e=f")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; c=d; domain=abc")
cookie_jar.add("e=f; domain=.abc")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d; e=f")
cookie_jar = SimpleCookieJar()
cookie_jar.add("a=b; c=d; domain=abc")
cookie_jar.add("e=f; domain=xyz")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
self.assertEquals(cookie_jar.get("xyz"), "e=f")
self.assertEquals(cookie_jar.get("something"), "")
示例10: testSet
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def testSet(self):
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b")
self.assertFalse(cookie_jar.jar, "Cookie with no domain should not be added to the jar")
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; domain=.abc")
self.assertTrue(".abc" in cookie_jar.jar)
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; domain=abc")
self.assertTrue(".abc" in cookie_jar.jar)
self.assertTrue("abc" not in cookie_jar.jar)
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; c=d; domain=abc")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; c=d; domain=abc")
cookie_jar.set("e=f; domain=abc")
self.assertEquals(cookie_jar.get("abc"), "e=f")
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; c=d; domain=abc")
cookie_jar.set("e=f; domain=.abc")
self.assertEquals(cookie_jar.get("abc"), "e=f")
cookie_jar = SimpleCookieJar()
cookie_jar.set("a=b; c=d; domain=abc")
cookie_jar.set("e=f; domain=xyz")
self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
self.assertEquals(cookie_jar.get("xyz"), "e=f")
self.assertEquals(cookie_jar.get("something"), "")
示例11: session_cookie
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def session_cookie(request):
cookie = request.cookies.get("JSESSIONID", "dummy")
cookies = http.cookies.SimpleCookie()
cookies["JSESSIONID"] = cookie
cookies["JSESSIONID"]["path"] = "/"
return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),)
示例12: __init__
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def __init__(self, *args, **kwargs):
self.cookies = None
self.path = None
self.wfile = None
self._wfile = None
self.server = args[2]
self.headers_active = False
"""Whether or not the request is in the sending headers phase."""
self.handler_map = {}
"""The dictionary object which maps regular expressions of resources to the functions which should handle them."""
self.rpc_handler_map = {}
"""The dictionary object which maps regular expressions of RPC functions to their handlers."""
for map_name in (None, self.__class__.__name__):
handler_map = g_handler_map.get(map_name, {})
for path, function_info in handler_map.items():
function, function_is_rpc = function_info
if function_is_rpc:
self.rpc_handler_map[path] = function
else:
self.handler_map[path] = function
self.basic_auth_user = None
"""The name of the user if the current request is using basic authentication."""
self.query_data = None
"""The parameter data that has been passed to the server parsed as a dict."""
self.raw_query_data = None
"""The raw data that was parsed into the :py:attr:`.query_data` attribute."""
self.__config = self.server.get_config()
"""A reference to the configuration provided by the server."""
self.on_init()
super(RequestHandler, self).__init__(*args, **kwargs)
示例13: cookie_get
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def cookie_get(self, name):
"""
Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found.
"""
if not hasattr(self, 'cookies'):
return None
if self.cookies.get(name):
return self.cookies.get(name).value
return None
示例14: test_other_http_imports
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def test_other_http_imports(self):
import http
import http.server
import http.cookies
import http.cookiejar
self.assertTrue(True)
示例15: get_param
# 需要导入模块: import http [as 别名]
# 或者: from http import cookies [as 别名]
def get_param(self, para_type, para_name):
"""
获取HTTP请求的某个变量
Parameters:
para_type - str, 参数类型,可选get, post, cookies, headers, json, files, body
para_name - str, 参数名, 当para_type为json时, para_name应为一个list,包含json path每一级的key
当para_type为files时, para_name应为一个包含两个item的list, 第一个指定要获取的files dict的下标, 第二个指定在dict中获取的key, 同set_param
Returns:
获取目标变量的值
Raises:
exceptions.DataParamError - 参数错误引发此异常
"""
if para_type == "cookies":
return self.http_data["cookies"].get(para_name, None)
elif para_type == "get":
return self.http_data["params"].get(para_name, None)
elif para_type == "post":
return self.http_data["data"].get(para_name, None)
elif para_type == "headers":
return self.http_data["headers"].get(para_name, None)
elif para_type == "json":
json_target = self.http_data["json"]
for name in para_name:
json_target = json_target[name]
return json_target
elif para_type == "files":
return self.http_data["files"][para_name[0]][para_name[1]]
elif para_type == "body":
return self.http_data["body"]
else:
Logger.error("Use an invalid para_type in get_param method!")
raise exceptions.DataTypeNotExist