Python http.cookiejar() Examples

The following are 30 code examples of http.cookiejar(). 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 , or try the search function .
Example #1
Source File: reqman.py    From reqman with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self,d=None):
        if not d: d={}

        if isinstance(d,str):
            d=ustr(d)
            try:
                d=yaml.load(d, Loader=yaml.FullLoader)
            except Exception as e:
                raise RMFormatException("Env conf is not yaml")

        if type(d) not in [dict,Env]:
            # raise RMFormatException("Env conf is not a dict %s" % str(d))
            d={}

        self.__shared={} # shared saved scope between all cloned Env
        self.__global={} # shared global saved scope between all cloned Env (from BEGIN only)

        dict.__init__(self,dict(d))
        self.cookiejar = CookieStore() 
Example #2
Source File: obs_operator.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def oscrc_create(self, oscrc_file, apiurl, cookiejar_file, user):
        sentry_dsn = sentry_client().dsn
        sentry_environment = sentry_client().options.get('environment')

        oscrc_file.write('\n'.join([
            '[general]',
            # Passthru sentry_sdk options to allow for reporting on subcommands.
            'sentry_sdk.dsn = {}'.format(sentry_dsn) if sentry_dsn else '',
            'sentry_sdk.environment = {}'.format(sentry_environment) if sentry_environment else '',
            'apiurl = {}'.format(apiurl),
            'cookiejar = {}'.format(cookiejar_file.name),
            'staging.color = 0',
            '[{}]'.format(apiurl),
            'user = {}'.format(user),
            'pass = invalid',
            '',
        ]).encode('utf-8'))
        oscrc_file.flush()

        # In order to avoid osc clearing the cookie file the modified time of
        # the oscrc file must be set further into the past.
        # if int(round(config_mtime)) > int(os.stat(cookie_file).st_mtime):
        recent_past = time.time() - 3600
        os.utime(oscrc_file.name, (recent_past, recent_past)) 
Example #3
Source File: __init__.py    From browser_cookie3 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def load(self):
        con = sqlite3.connect(self.tmp_cookie_file)
        cur = con.cursor()
        cur.execute('select host, path, isSecure, expiry, name, value from moz_cookies '
                    'where host like "%{}%"'.format(self.domain_name))

        cj = http.cookiejar.CookieJar()
        for item in cur.fetchall():
            c = create_cookie(*item)
            cj.set_cookie(c)
        con.close()

        self.__add_session_cookies(cj)
        self.__add_session_cookies_lz4(cj)

        return cj 
Example #4
Source File: request.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def __init__(self, cookiejar=None):
        import http.cookiejar
        if cookiejar is None:
            cookiejar = http.cookiejar.CookieJar()
        self.cookiejar = cookiejar 
Example #5
Source File: request.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, cookiejar=None):
        import http.cookiejar
        if cookiejar is None:
            cookiejar = http.cookiejar.CookieJar()
        self.cookiejar = cookiejar 
Example #6
Source File: request.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def http_request(self, request):
        self.cookiejar.add_cookie_header(request)
        return request 
Example #7
Source File: request.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def http_response(self, request, response):
        self.cookiejar.extract_cookies(response, request)
        return response 
Example #8
Source File: request.py    From Imogen with MIT License 5 votes vote down vote up
def __init__(self, cookiejar=None):
        import http.cookiejar
        if cookiejar is None:
            cookiejar = http.cookiejar.CookieJar()
        self.cookiejar = cookiejar 
Example #9
Source File: request.py    From Imogen with MIT License 5 votes vote down vote up
def http_request(self, request):
        self.cookiejar.add_cookie_header(request)
        return request 
Example #10
Source File: request.py    From Imogen with MIT License 5 votes vote down vote up
def http_response(self, request, response):
        self.cookiejar.extract_cookies(response, request)
        return response 
Example #11
Source File: test_standard_library.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 5 votes vote down vote up
def test_other_http_imports(self):
        import http
        import http.server
        import http.cookies
        import http.cookiejar
        self.assertTrue(True) 
Example #12
Source File: request.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def http_request(self, request):
        self.cookiejar.add_cookie_header(request)
        return request 
Example #13
Source File: request.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def http_response(self, request, response):
        self.cookiejar.extract_cookies(response, request)
        return response 
Example #14
Source File: request.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, cookiejar=None):
        import http.cookiejar
        if cookiejar is None:
            cookiejar = http.cookiejar.CookieJar()
        self.cookiejar = cookiejar 
Example #15
Source File: request.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def http_request(self, request):
        self.cookiejar.add_cookie_header(request)
        return request 
Example #16
Source File: request.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def http_response(self, request, response):
        self.cookiejar.extract_cookies(response, request)
        return response 
Example #17
Source File: requests_html.py    From requests-html with MIT License 5 votes vote down vote up
def _convert_cookiesjar_to_render(self):
        """
        Convert HTMLSession.cookies for browser.newPage().setCookie
        Return a list of dict
        """
        cookies_render = []
        if isinstance(self.session.cookies, http.cookiejar.CookieJar):
            for cookie in self.session.cookies:
                cookies_render.append(self._convert_cookiejar_to_render(cookie))
        return cookies_render 
Example #18
Source File: __init__.py    From browser_cookie3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def firefox(cookie_file=None, domain_name=""):
    """Returns a cookiejar of the cookies and sessions used by Firefox. Optionally
    pass in a domain name to only load cookies from the specified domain
    """
    return Firefox(cookie_file, domain_name).load() 
Example #19
Source File: __init__.py    From browser_cookie3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def chrome(cookie_file=None, domain_name=""):
    """Returns a cookiejar of the cookies used by Chrome. Optionally pass in a
    domain name to only load cookies from the specified domain
    """
    return Chrome(cookie_file, domain_name).load() 
Example #20
Source File: __init__.py    From browser_cookie3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_cookie(host, path, secure, expires, name, value):
    """Shortcut function to create a cookie
    """
    return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path,
                                 True, secure, expires, False, None, None, {}) 
Example #21
Source File: __init__.py    From browser_cookie3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def load(self):
        """Load sqlite cookies into a cookiejar
        """
        con = sqlite3.connect(self.tmp_cookie_file)
        cur = con.cursor()
        try:
            # chrome <=55
            cur.execute('SELECT host_key, path, secure, expires_utc, name, value, encrypted_value '
                        'FROM cookies WHERE host_key like "%{}%";'.format(self.domain_name))
        except sqlite3.OperationalError:
            # chrome >=56
            cur.execute('SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value '
                        'FROM cookies WHERE host_key like "%{}%";'.format(self.domain_name))

        cj = http.cookiejar.CookieJar()
        epoch_start = datetime.datetime(1601, 1, 1)
        for item in cur.fetchall():
            host, path, secure, expires, name = item[:5]
            if item[3] != 0:
                # ensure dates don't exceed the datetime limit of year 10000
                try:
                    offset = min(int(item[3]), 265000000000000000)
                    delta = datetime.timedelta(microseconds=offset)
                    expires = epoch_start + delta
                    expires = expires.timestamp()
                # Windows 7 has a further constraint
                except OSError:
                    offset = min(int(item[3]), 32536799999000000)
                    delta = datetime.timedelta(microseconds=offset)
                    expires = epoch_start + delta
                    expires = expires.timestamp()

            value = self._decrypt(item[5], item[6])
            c = create_cookie(host, path, secure, expires, name, value)
            cj.set_cookie(c)
        con.close()
        return cj 
Example #22
Source File: DbCookieJar.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load(self, filename=None, ignore_discard=False, ignore_expires=False):
		if self.exit_saved:
			return

		assert self.headers != None
		for _ in range(10):
			try:
				with self.db.session_context("cookiejar") as sess:
					self.__load_cookies(sess)
					sess.commit()
				return
			except sqlalchemy.exc.SQLAlchemyError:
				pass 
Example #23
Source File: DbCookieJar.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
		if self.exit_saved:
			return

		assert self.headers != None
		for _ in range(10):
			try:
				with self.db.session_context("cookiejar") as sess:
					self.__save_cookies(sess)
					sess.commit()
				return
			except sqlalchemy.exc.SQLAlchemyError:
				pass 
Example #24
Source File: DbCookieJar.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sync_cookies(self):
		assert self.headers != None
		with self.db.session_context("cookiejar") as sess:
			self.__save_cookies(sess)
			self.__load_cookies(sess)
			sess.commit() 
Example #25
Source File: DbCookieJar.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __load_cookies(self, sess):

		have = sess.query(db.WebCookieDb)                                           \
			.filter(db.WebCookieDb.ua_user_agent        == self.headers['User-Agent'])      \
			.filter(db.WebCookieDb.ua_accept_language   == self.headers['Accept-Language']) \
			.filter(db.WebCookieDb.ua_accept            == self.headers['Accept'])          \
			.filter(db.WebCookieDb.ua_accept_encoding   == self.headers['Accept-Encoding']) \
			.all()

		for cookie in have:
			new_ck = http.cookiejar.Cookie(
				version            = cookie.c_version,
				name               = cookie.c_name,
				value              = cookie.c_value,
				port               = cookie.c_port,
				port_specified     = cookie.c_port_specified,
				domain             = cookie.c_domain,
				domain_specified   = cookie.c_domain_specified,
				domain_initial_dot = cookie.c_domain_initial_dot,
				path               = cookie.c_path,
				path_specified     = cookie.c_path_specified,
				secure             = cookie.c_secure,
				expires            = cookie.c_expires,
				discard            = cookie.c_discard,
				comment            = cookie.c_comment,
				comment_url        = cookie.c_comment_url,
				rest               = json.loads(cookie.c_rest),
				rfc2109            = cookie.c_rfc2109,
				)
			self.set_cookie(new_ck)

		self.log.info("Loaded %s cookies from db.", len(have))

		sess.commit() 
Example #26
Source File: DbCookieJar.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, db, session, policy=None):
		http.cookiejar.CookieJar.__init__(self, policy)

		self.log = logging.getLogger("Main.DbCookieJar")

		self.headers = None
		self.db      = db

		self.exit_saved = False
		atexit.register(self._save_at_exit) 
Example #27
Source File: reqman.py    From reqman with GNU General Public License v2.0 5 votes vote down vote up
def __setstate__(self, state):
        self.__dict__=state
        self.__shared={}
        self.__global={}
        self.cookiejar = CookieStore() 
Example #28
Source File: reqman.py    From reqman with GNU General Public License v2.0 5 votes vote down vote up
def clone(self,cloneSharedScope=True):
        newOne=Env({})
        dict_merge(newOne,self)
        newOne.cookiejar= CookieStore( self.cookiejar.export() )

        dict_merge(newOne,self.__global) # declare those of the global scope !!! (from BEGIN only)
        newOne.__global = self.__global  #mk a ref to global

        if cloneSharedScope: #used (at false) at each Reqs() constructor (to start on a sane base)
            dict_merge(newOne,self.__shared) # declare those of the shared scope !!!
            newOne.__shared = self.__shared  #mk a ref to shared
        return newOne 
Example #29
Source File: reqman.py    From reqman with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, ll: T.List[dict]=[]) -> None:
        http.cookiejar.CookieJar.__init__(self)
        for c in ll:
            self.set_cookie( http.cookiejar.Cookie(**c) ) 
Example #30
Source File: test_standard_library.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 4 votes vote down vote up
def test_future_moves(self):
        """
        Ensure everything is available from the future.moves interface that we
        claim and expect. (Issue #104).
        """
        from future.moves.collections import Counter, OrderedDict   # backported to Py2.6
        from future.moves.collections import UserDict, UserList, UserString

        from future.moves import configparser
        from future.moves import copyreg

        from future.moves.itertools import filterfalse, zip_longest

        from future.moves import html
        import future.moves.html.entities
        import future.moves.html.parser

        from future.moves import http
        import future.moves.http.client
        import future.moves.http.cookies
        import future.moves.http.cookiejar
        import future.moves.http.server

        from future.moves import queue

        from future.moves import socketserver

        from future.moves.subprocess import check_output              # even on Py2.6
        from future.moves.subprocess import getoutput, getstatusoutput

        from future.moves.sys import intern

        from future.moves import urllib
        import future.moves.urllib.error
        import future.moves.urllib.parse
        import future.moves.urllib.request
        import future.moves.urllib.response
        import future.moves.urllib.robotparser

        try:
            # Is _winreg available on Py2? If so, ensure future.moves._winreg is available too:
            import _winreg
        except ImportError:
            pass
        else:
            from future.moves import winreg

        from future.moves import xmlrpc
        import future.moves.xmlrpc.client
        import future.moves.xmlrpc.server

        from future.moves import _dummy_thread
        from future.moves import _markupbase
        from future.moves import _thread