本文整理汇总了Python中requests.cookies.RequestsCookieJar方法的典型用法代码示例。如果您正苦于以下问题:Python cookies.RequestsCookieJar方法的具体用法?Python cookies.RequestsCookieJar怎么用?Python cookies.RequestsCookieJar使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests.cookies
的用法示例。
在下文中一共展示了cookies.RequestsCookieJar方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_cookie_dict
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def test_cookie_dict():
c = RetsHttpClient('login_url', 'username', 'password')
c._session = mock.MagicMock()
jar = RequestsCookieJar()
c1 = Cookie(1, 'name1', 'value1', 80, 80, 'domain', 'domain_specified', 'domain_initial_dot', 'path',
'path_specified', True, True, False, 'comment', 'comment_url', 'rest')
c2 = Cookie(1, 'name2', 'value2', 80, 80, 'domain', 'domain_specified', 'domain_initial_dot', 'path',
'path_specified', True, True, False, 'comment', 'comment_url', 'rest')
c3 = Cookie(1, 'name1', 'value1', 80, 80, 'domain', 'domain_specified3', 'domain_initial_dot3', 'path3',
'path_specified3', True, True, False, 'comment', 'comment_url', 'rest')
jar.set_cookie(c1)
jar.set_cookie(c2)
jar.set_cookie(c3)
c._session.cookies = jar
assert c.cookie_dict == {'name1': 'value1', 'name2': 'value2'}
示例2: load_and_merge_cookie_jars
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def load_and_merge_cookie_jars(cookie_jar_paths):
cookie_jar = RequestsCookieJar()
if not cookie_jar_paths:
return cookie_jar
logging.debug("Attempting to load and merge the following cookie files: %s" % cookie_jar_paths)
for f in cookie_jar_paths:
if os.path.isfile(f):
try:
cookies = MozillaCookieJar(f)
cookies.load(ignore_expires=True, ignore_discard=True)
cookie_jar.update(cookies)
except Exception as e:
logging.warning("Unable to load cookie file [%s]: %s" % (f, get_typed_exception(e)))
# Do not preserve expire values from cookies with expires=0 from the file, or requests will not use the cookie
for cookie in iter(cookie_jar):
if not cookie.expires:
cookie.expires = None
return cookie_jar
示例3: init_cookie_jar
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def init_cookie_jar(cookie_file=None, cookie_t=None, cookie_y=None, cookie_euconsent=None):
cookie_jar = LWPCookieJar(cookie_file) if cookie_file else RequestsCookieJar()
if cookie_file and os.path.exists(cookie_file):
cookie_jar.load(ignore_discard=True)
if args.cookie_t:
cookie_jar.set_cookie(create_cookie('T', cookie_t))
if cookie_y:
cookie_jar.set_cookie(create_cookie('Y', cookie_y))
if cookie_euconsent:
cookie_jar.set_cookie(create_cookie('EuConsent', cookie_euconsent))
if cookie_file:
cookie_jar.save(ignore_discard=True)
return cookie_jar
示例4: _handle_basic_auth_401
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def _handle_basic_auth_401(self, r, kwargs):
if self.pos is not None:
r.request.body.seek(self.pos)
# Consume content and release the original connection
# to allow our new request to reuse the same one.
r.content
r.raw.release_conn()
prep = r.request.copy()
if not hasattr(prep, '_cookies'):
prep._cookies = cookies.RequestsCookieJar()
cookies.extract_cookies_to_jar(prep._cookies, r.request, r.raw)
prep.prepare_cookies(prep._cookies)
self.auth = auth.HTTPBasicAuth(self.username, self.password)
prep = self.auth(prep)
_r = r.connection.send(prep, **kwargs)
_r.history.append(r)
_r.request = prep
return _r
示例5: _handle_basic_auth_407
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def _handle_basic_auth_407(self, r, kwargs):
if self.pos is not None:
r.request.body.seek(self.pos)
r.content
r.raw.release_conn()
prep = r.request.copy()
if not hasattr(prep, '_cookies'):
prep._cookies = cookies.RequestsCookieJar()
cookies.extract_cookies_to_jar(prep._cookies, r.request, r.raw)
prep.prepare_cookies(prep._cookies)
self.proxy_auth = auth.HTTPProxyAuth(self.proxy_username,
self.proxy_password)
prep = self.proxy_auth(prep)
_r = r.connection.send(prep, **kwargs)
_r.history.append(r)
_r.request = prep
return _r
示例6: get_score
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def get_score(cookies):
try:
jar = RequestsCookieJar()
for cookie in cookies:
jar.set(cookie['name'], cookie['value'])
total = requests.get("https://pc-api.xuexi.cn/open/api/score/get", cookies=jar).content.decode("utf8")
total = int(json.loads(total, encoding="utf8")["data"]["score"])
each = requests.get("https://pc-api.xuexi.cn/open/api/score/today/queryrate", cookies=jar).content.decode(
"utf8")
each = json.loads(each, encoding="utf8")["data"]["dayScoreDtos"]
each = [int(i["currentScore"]) for i in each if i["ruleId"] in [1, 2, 9, 1002, 1003]]
return total, each
except:
print("=" * 120)
print("get_video_links获取失败")
print("=" * 120)
raise
示例7: get_prepared_request
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def get_prepared_request(data: Dict[str, Any]) -> requests.PreparedRequest:
"""Create a `requests.PreparedRequest` from a serialized one."""
prepared = requests.PreparedRequest()
prepared.method = data["method"]
prepared.url = data["uri"]
prepared._cookies = RequestsCookieJar() # type: ignore
encoded = data["body"]["base64_string"]
if encoded:
prepared.body = base64.b64decode(encoded)
# There is always 1 value in a request
headers = [(key, value[0]) for key, value in data["headers"].items()]
prepared.headers = CaseInsensitiveDict(headers)
return prepared
示例8: addcookies
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def addcookies(self, cookies):
"""Inject Cookies from a CookieJar into our JSON dictionary."""
if not isinstance(cookies, RequestsCookieJar):
return False
for domain, pathdict in cookies._cookies.items():
search_ip = IP_REGEX.match(domain)
if search_ip:
# Match either an IPv4 address or an IPv6 address with a local suffix
domain_key = search_ip.group("ip")
else:
domain_key = domain if domain[0] == '.' else '.' + domain
if domain_key not in self.cookiedict.keys():
self.cookiedict[domain_key] = {}
for path, keydict in pathdict.items():
if path not in self.cookiedict[domain_key].keys():
self.cookiedict[domain_key][path] = {}
for key, cookieobj in keydict.items():
if isinstance(cookieobj, Cookie):
print(cookieobj)
cookie_attrs = {
"value": cookieobj.value,
"expires": cookieobj.expires,
"secure": cookieobj.secure,
"port": cookieobj.port,
"version": cookieobj.version
}
self.cookiedict[domain_key][path][key] = cookie_attrs
示例9: cookies
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def cookies():
cookies = RequestsCookieJar()
cookies.set('T', 't_cookie')
cookies.set('Y', 'y_cookie')
cookies.set('EuConsent', 'eu_cookie')
yield cookies
示例10: test_client_sends_cookies
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def test_client_sends_cookies():
s = requests.Session()
s.cookies = RequestsCookieJar()
s.cookies['foo'] = 'bar'
with mock.patch('sseclient.requests.Session.send') as m:
m.return_value.encoding = "utf-8"
sseclient.SSEClient('http://blah.com', session=s)
prepared_request = m.call_args[0][0]
assert prepared_request.headers['Cookie'] == 'foo=bar'
示例11: test_set_cookiejar
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def test_set_cookiejar(httpbin):
"""Set cookies locally and test that they are received remotely."""
# construct a phony cookiejar and attach it to the session
jar = RequestsCookieJar()
jar.set('field', 'value')
assert jar.get('field') == 'value'
browser = mechanicalsoup.Browser()
browser.set_cookiejar(jar)
resp = browser.get(httpbin + "/cookies")
assert resp.json() == {'cookies': {'field': 'value'}}
示例12: test_bad_get_body
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def test_bad_get_body(self, req, includes):
"""Can't add a body with a GET request
"""
req["method"] = "GET"
with pytest.warns(RuntimeWarning):
RestRequest(
Mock(spec=requests.Session, cookies=RequestsCookieJar()), req, includes
)
示例13: mock_session
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def mock_session(self):
return Mock(spec=requests.Session, cookies=RequestsCookieJar())
示例14: test_available_not_waited
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def test_available_not_waited(self, req, includes):
"""some available but not set"""
cookiejar = RequestsCookieJar()
cookiejar.set("a", 2)
mock_session = Mock(spec=requests.Session, cookies=cookiejar)
assert _read_expected_cookies(mock_session, req, includes) == None
示例15: test_ask_for_nothing
# 需要导入模块: from requests import cookies [as 别名]
# 或者: from requests.cookies import RequestsCookieJar [as 别名]
def test_ask_for_nothing(self, req, includes):
"""explicitly ask fo rno cookies"""
cookiejar = RequestsCookieJar()
cookiejar.set("a", 2)
mock_session = Mock(spec=requests.Session, cookies=cookiejar)
req["cookies"] = []
assert _read_expected_cookies(mock_session, req, includes) == {}