Python http.cookiejar.FileCookieJar() Examples

The following are 10 code examples of http.cookiejar.FileCookieJar(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module http.cookiejar , or try the search function .
Example #1
Source File: gocookies.py    From python-libjuju with Apache License 2.0 6 votes vote down vote up
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)) 
Example #2
Source File: sumologic.py    From sumologic-python-sdk with Apache License 2.0 5 votes vote down vote up
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") 
Example #3
Source File: gocookies.py    From python-libjuju with Apache License 2.0 5 votes vote down vote up
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) 
Example #4
Source File: connection.py    From wiki-scripts with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #5
Source File: auth.py    From terminal-leetcode with MIT License 5 votes vote down vote up
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 
Example #6
Source File: api.py    From 115wangpan with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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() 
Example #7
Source File: api.py    From 115wangpan with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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) 
Example #8
Source File: http.py    From JWTConnect-Python-OidcRP with Apache License 2.0 5 votes vote down vote up
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 
Example #9
Source File: connection.py    From wiki-scripts with GNU General Public License v3.0 4 votes vote down vote up
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 
Example #10
Source File: test_03_util.py    From JWTConnect-Python-OidcRP with Apache License 2.0 4 votes vote down vote up
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"