本文整理汇总了Python中http.cookiejar.FileCookieJar方法的典型用法代码示例。如果您正苦于以下问题:Python cookiejar.FileCookieJar方法的具体用法?Python cookiejar.FileCookieJar怎么用?Python cookiejar.FileCookieJar使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.cookiejar
的用法示例。
在下文中一共展示了cookiejar.FileCookieJar方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
'''Implement the FileCookieJar abstract method.'''
if filename is None:
if self.filename is not None:
filename = self.filename
else:
raise ValueError(cookiejar.MISSING_FILENAME_TEXT)
# TODO: obtain file lock, read contents of file, and merge with
# current content.
go_cookies = []
now = time.time()
for cookie in self:
if not ignore_discard and cookie.discard:
continue
if not ignore_expires and cookie.is_expired(now):
continue
go_cookies.append(py_to_go_cookie(cookie))
with open(filename, "w") as f:
f.write(json.dumps(go_cookies))
示例2: __init__
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def __init__(self, accessId, accessKey, endpoint=None, caBundle=None, cookieFile='cookies.txt'):
self.session = requests.Session()
self.session.auth = (accessId, accessKey)
self.DEFAULT_VERSION = 'v1'
self.session.headers = {'content-type': 'application/json', 'accept': 'application/json'}
if caBundle is not None:
self.session.verify = caBundle
cj = cookielib.FileCookieJar(cookieFile)
self.session.cookies = cj
if endpoint is None:
self.endpoint = self._get_endpoint()
else:
self.endpoint = endpoint
if self.endpoint[-1:] == "/":
raise Exception("Endpoint should not end with a slash character")
示例3: _really_load
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def _really_load(self, f, filename, ignore_discard, ignore_expires):
'''Implement the _really_load method called by FileCookieJar
to implement the actual cookie loading'''
data = json.load(f) or []
now = time.time()
for cookie in map(go_to_py_cookie, data):
if not ignore_expires and cookie.is_expired(now):
continue
self.set_cookie(cookie)
示例4: request
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def request(self, method, url, **kwargs):
"""
Simple HTTP request handler. It is basically a wrapper around
:py:func:`requests.request()` using the established session including
cookies, so it should be used only for connections with ``url`` leading
to the same site.
The parameters are the same as for :py:func:`requests.request()`, see
`Requests documentation`_ for details.
There is no translation of exceptions, the :py:mod:`requests` exceptions
(notably :py:exc:`requests.exceptions.ConnectionError`,
:py:exc:`requests.exceptions.Timeout` and
:py:exc:`requests.exceptions.HTTPError`) should be catched by the caller.
.. _`Requests documentation`: http://docs.python-requests.org/en/latest/api/
"""
response = self.session.request(method, url, timeout=self.timeout, **kwargs)
# raise HTTPError for bad requests (4XX client errors and 5XX server errors)
response.raise_for_status()
if isinstance(self.session.cookies, cookielib.FileCookieJar):
self.session.cookies.save()
return response
示例5: get_cookies_from_local_file
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def get_cookies_from_local_file(self):
COOKIE_PATH = os.path.join(CONFIG_FOLDER, 'cookies')
self.cookies = cookiejar.FileCookieJar(COOKIE_PATH)
try:
self.cookies.load(ignore_discard=True)
except Exception:
pass
示例6: __init__
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def __init__(self, persistent=False,
cookies_filename=None, cookies_type='LWPCookieJar'):
"""
:param bool auto_logout: whether to logout automatically when
:class:`.API` object is destroyed
.. deprecated:: 0.6.0
Call :meth:`.API.logout` explicitly
:param bool persistent: whether to use persistent session that stores
cookies on disk
:param str cookies_filename: path to the cookies file, use default
path (`~/.115cookies`) if None
:param str cookies_type: a string representing
:class:`cookielib.FileCookieJar` subclass,
`LWPCookieJar` (default) or `MozillaCookieJar`
"""
self.persistent = persistent
self.cookies_filename = cookies_filename
self.cookies_type = cookies_type
self.passport = None
self.http = RequestHandler()
self.logger = logging.getLogger(conf.LOGGING_API_LOGGER)
# Cache attributes to decrease API hits
self._user_id = None
self._username = None
self._signatures = {}
self._upload_url = None
self._lixian_timestamp = None
self._root_directory = None
self._downloads_directory = None
self._receiver_directory = None
self._torrents_directory = None
self._task_count = None
self._task_quota = None
if self.persistent:
self.load_cookies()
示例7: save_cookies
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def save_cookies(self, ignore_discard=True, ignore_expires=True):
"""Save cookies to the file :attr:`.API.cookies_filename`"""
if not isinstance(self.cookies, cookielib.FileCookieJar):
m = 'Cookies must be a cookielib.FileCookieJar object to be saved.'
raise APIError(m)
self.cookies.save(ignore_discard=ignore_discard,
ignore_expires=ignore_expires)
示例8: __init__
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def __init__(self, httpc_params=None):
"""
A base class for OAuth2 clients and servers
:param httpc_params: Default arguments to be used for HTTP requests
"""
self.request_args = {"allow_redirects": False}
if httpc_params:
self.request_args.update(httpc_params)
self.cookiejar = FileCookieJar()
self.events = None
self.req_callback = None
示例9: make_session
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def make_session(user_agent=DEFAULT_UA, ssl_verify=None, max_retries=0,
cookie_file=None, cookiejar=None,
http_user=None, http_password=None):
"""
Creates a :py:class:`requests.Session` object for the connection.
It is possible to save the session data by specifying either ``cookiejar``
or ``cookie_file`` arguments. If ``cookiejar`` is present, ``cookie_file``
is ignored.
:param str user_agent: string sent as ``User-Agent`` header to the web server
:param bool ssl_verify: if ``True``, the SSL certificate will be verified
:param int max_retries:
Maximum number of retries for each connection. Applies only to
failed DNS lookups, socket connections and connection timeouts, never
to requests where data has made it to the server.
:param str cookie_file: path to a :py:class:`cookielib.FileCookieJar` file
:param cookiejar: an existing :py:class:`cookielib.CookieJar` object
:returns: :py:class:`requests.Session` object
"""
session = requests.Session()
if cookiejar is not None:
session.cookies = cookiejar
elif cookie_file is not None:
session.cookies = cookielib.LWPCookieJar(cookie_file)
try:
session.cookies.load()
except (cookielib.LoadError, FileNotFoundError):
session.cookies.save()
session.cookies.load()
_auth = None
if http_user is not None and http_password is not None:
_auth = (http_user, http_password)
session.headers.update({"user-agent": user_agent})
session.auth = _auth
session.params.update({"format": "json"})
session.verify = ssl_verify
# granular control over requests' retries: https://stackoverflow.com/a/35504626
retries = Retry(total=max_retries, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
adapter = requests.adapters.HTTPAdapter(max_retries=retries)
session.mount("https://", adapter)
session.mount("http://", adapter)
return session
示例10: test_set_cookie
# 需要导入模块: from http import cookiejar [as 别名]
# 或者: from http.cookiejar import FileCookieJar [as 别名]
def test_set_cookie():
cookiejar = FileCookieJar()
_cookie = {"value_0": "v_0", "value_1": "v_1", "value_2": "v_2"}
c = SimpleCookie(_cookie)
domain_0 = ".test_domain"
domain_1 = "test_domain"
max_age = "09 Feb 1994 22:23:32 GMT"
expires = http2time(max_age)
path = "test/path"
c["value_0"]["max-age"] = max_age
c["value_0"]["domain"] = domain_0
c["value_0"]["path"] = path
c["value_1"]["domain"] = domain_1
util.set_cookie(cookiejar, c)
cookies = cookiejar._cookies
c_0 = cookies[domain_0][path]["value_0"]
c_1 = cookies[domain_1][""]["value_1"]
c_2 = cookies[""][""]["value_2"]
assert not (c_2.domain_specified and c_2.path_specified)
assert c_1.domain_specified and not c_1.domain_initial_dot and not \
c_1.path_specified
assert c_0.domain_specified and c_0.domain_initial_dot and \
c_0.path_specified
assert c_0.expires == expires
assert c_0.domain == domain_0
assert c_0.name == "value_0"
assert c_0.path == path
assert c_0.value == "v_0"
assert not c_1.expires
assert c_1.domain == domain_1
assert c_1.name == "value_1"
assert c_1.path == ""
assert c_1.value == "v_1"
assert not c_2.expires
assert c_2.domain == ""
assert c_2.name == "value_2"
assert c_2.path == ""
assert c_2.value == "v_2"