Python http.cookiejar 模块,Cookie() 实例源码

我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用http.cookiejar.Cookie()

项目:jabbapylib3    作者:jabbalaci    | 项目源码 | 文件源码
def get_cookies_in_cookiejar(host):
    """Export cookies and put them in a cookiejar.

    Return value: a cookiejar filled with cookies."""
    # based on http://www.guyrutenberg.com/2010/11/27/building-cookiejar-out-of-firefoxs-cookies-sqlite/
    cj = LWPCookieJar()       # This is a subclass of FileCookieJar that has useful load and save methods

    cookie_db = get_cookie_db_path(str(FIREFOX_DIR))
    conn = db.connect(cookie_db)
    cursor = conn.cursor()
    sql = "SELECT {c} FROM moz_cookies WHERE host LIKE '%{h}%'".format(c=CONTENTS, h=host)
    cursor.execute(sql)

    for item in cursor.fetchall():
        c = Cookie(0, item[4], item[5],
            None, False,
            item[0], item[0].startswith('.'), item[0].startswith('.'),
            item[1], False,
            item[2],
            item[3], item[3]=="",
            None, None, {})
        #print c
        cj.set_cookie(c)

    return cj
项目:DPLib    作者:mRokita    | 项目源码 | 文件源码
def set_sessid(self, session_id):
        """
        Set session id to session_id.
        Used to "fake" session_id, pretty useful for hijacking ;)

        :param session_id: session id to set

        :return: None
        :rtype: NoneType
        """
        self.session_id = session_id
        self.__cj.set_cookie(Cookie(name="PHPSESSID", value=session_id,
                                    port=None, port_specified=False,
                                    domain='dplogin.com',
                                    domain_specified=False,
                                    domain_initial_dot=False, path='/',
                                    secure=False, expires=None, discard=True,
                                    comment=None, rest={'HttpOnly': None},
                                    rfc2109=False, comment_url=None,
                                    path_specified=False, version=0))
项目:http-observatory    作者:mozilla    | 项目源码 | 文件源码
def test_regular_cookie_no_secure_but_hsts(self):
        cookie = Cookie(name='foo',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={},
                        secure=False,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)
        self.reqs['responses']['https'].headers['Strict-Transport-Security'] = 'max-age=15768000'

        result = cookies(self.reqs)

        self.assertEquals('cookies-without-secure-flag-but-protected-by-hsts', result['result'])
        self.assertFalse(result['pass'])
项目:http-observatory    作者:mozilla    | 项目源码 | 文件源码
def test_session_cookie_no_secure_but_hsts(self):
        cookie = Cookie(name='SESSIONID',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={'HttpOnly': True},
                        secure=False,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)
        self.reqs['responses']['https'].headers['Strict-Transport-Security'] = 'max-age=15768000'

        result = cookies(self.reqs)

        self.assertEquals('cookies-session-without-secure-flag-but-protected-by-hsts', result['result'])
        self.assertFalse(result['pass'])
项目:http-observatory    作者:mozilla    | 项目源码 | 文件源码
def test_no_secure(self):
        cookie = Cookie(name='foo',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={},
                        secure=False,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)

        result = cookies(self.reqs)

        self.assertEquals('cookies-without-secure-flag', result['result'])
        self.assertFalse(result['pass'])
项目:http-observatory    作者:mozilla    | 项目源码 | 文件源码
def test_session_no_httponly(self):
        cookie = Cookie(name='SESSIONID',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={},
                        secure=True,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)

        result = cookies(self.reqs)

        self.assertEquals('cookies-session-without-httponly-flag', result['result'])
        self.assertFalse(result['pass'])
项目:rets    作者:opendoor-labs    | 项目源码 | 文件源码
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'}
项目:data-hub-backend    作者:uktrade-attic    | 项目源码 | 文件源码
def mock_cookie(self):
        """
        Makes sure that the cookie is there.
        """
        from http.cookiejar import Cookie
        self.cookie_storage.write({
            'example.com': {
                '/': {
                    'NID': Cookie(
                        version=0, name='NID', value='0000', port=None, port_specified=False,
                        domain='example.com', domain_specified=True, domain_initial_dot=True,
                        path='/', path_specified=True, secure=False, expires=1476201395,
                        discard=False, comment=None, comment_url=None, rest={'HttpOnly': None},
                        rfc2109=False
                    )
                }
            }
        })
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def _new_py_cookie(go_cookie):
    '''Convert a Go-style JSON-unmarshaled cookie into a Python cookie'''
    expires = None
    if go_cookie.get('Expires') is not None:
        t = pyrfc3339.parse(go_cookie['Expires'])
        expires = t.strftime("%s")
    return cookiejar.Cookie(
        version=0,
        name=go_cookie['Name'],
        value=go_cookie['Value'],
        port=None,
        port_specified=False,
        # Unfortunately Python cookies don't record the original
        # host that the cookie came from, so we'll just use Domain
        # for that purpose, and record that the domain was specified,
        # even though it probably was not. This means that
        # we won't correctly record the CanonicalHost entry
        # when writing the cookie file after reading it.
        domain=go_cookie['Domain'],
        domain_specified=not go_cookie['HostOnly'],
        domain_initial_dot=False,
        path=go_cookie['Path'],
        path_specified=True,
        secure=go_cookie['Secure'],
        expires=expires,
        discard=False,
        comment=None,
        comment_url=None,
        rest=None,
        rfc2109=False,
    )
项目:browsercookie-windows-support    作者:DavidMetcalfe    | 项目源码 | 文件源码
def create_cookie(host, path, secure, expires, name, value):
    """Shortcut function to create a cookie
    """
    return cookielib.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path, True, secure, expires, False, None, None, {})
项目:PyQBot    作者:WuTianming    | 项目源码 | 文件源码
def set_cookie(self, name, value, domain, path='/', expires=None):
        self.cj.set_cookie(Cookie(
            version=0, name=name, value=value, port=None,
            port_specified=False, domain=domain, domain_specified=True,
            domain_initial_dot=False, path=path, path_specified=True,
            secure=False, expires=expires, discard=False, comment=None,
            comment_url=None, rest=None))
项目:PyQBot    作者:WuTianming    | 项目源码 | 文件源码
def get_cookie(self, name, domain, path='/'):
        try:
            return self.cj._cookies[domain][path][name].value
        except Exception:
            raise RuntimeError('Cookie not found:%s @ %s%s' % (
                name, domain, path))
项目:django-runner    作者:awecode    | 项目源码 | 文件源码
def to_py_cookie(QtCookie):
        port = None
        port_specified = False
        secure = QtCookie.isSecure()
        name = QtCookie.name().data().decode()
        value = QtCookie.value().data().decode()
        v = QtCookie.path()
        path_specified = bool(v != "")
        path = v if path_specified else None
        v = QtCookie.domain()
        domain_specified = bool(v != "")
        domain = v
        if domain_specified:
            domain_initial_dot = v.startswith('.')
        else:
            domain_initial_dot = None
        v = int(QtCookie.expirationDate().toTime_t())
        expires = 2147483647 if v > 2147483647 else v
        rest = {"HttpOnly": QtCookie.isHttpOnly()}
        discard = False
        return Cookie(
            0,
            name,
            value,
            port,
            port_specified,
            domain,
            domain_specified,
            domain_initial_dot,
            path,
            path_specified,
            secure,
            expires,
            discard,
            None,
            None,
            rest,
        )
项目:http-observatory    作者:mozilla    | 项目源码 | 文件源码
def test_session_no_secure(self):
        cookie = Cookie(name='SESSIONID',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={'HttpOnly': True},
                        secure=False,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)

        result = cookies(self.reqs)

        self.assertEquals('cookies-session-without-secure-flag', result['result'])
        self.assertFalse(result['pass'])

        # https://github.com/mozilla/http-observatory/issues/97
        cookie = Cookie(name='SESSIONID',
                        comment=None,
                        comment_url=None,
                        discard=False,
                        domain='mozilla.com',
                        domain_initial_dot=False,
                        domain_specified='mozilla.com',
                        expires=None,
                        path='/',
                        path_specified='/',
                        port=443,
                        port_specified=443,
                        rfc2109=False,
                        rest={},
                        secure=False,
                        version=1,
                        value='bar')
        self.reqs['session'].cookies.set_cookie(cookie)

        result = cookies(self.reqs)

        self.assertEquals('cookies-session-without-secure-flag', result['result'])
        self.assertFalse(result['pass'])
项目:rawr    作者:al14s    | 项目源码 | 文件源码
def save_cookies(self, cookie_storage):
        """Save to cookielib's CookieJar or Set-Cookie3 format text file.

        :param cookie_storage: file location string or CookieJar instance.
        """
        def toPyCookieJar(QtCookieJar, PyCookieJar):
            for c in QtCookieJar.allCookies():
                PyCookieJar.set_cookie(toPyCookie(c))

        def toPyCookie(QtCookie):
            port = None
            port_specified = False
            secure = QtCookie.isSecure()
            name = str(QtCookie.name())
            value = str(QtCookie.value())
            v = str(QtCookie.path())
            path_specified = bool(v != "")
            path = v if path_specified else None
            v = str(QtCookie.domain())
            domain_specified = bool(v != "")
            domain = v
            if domain_specified:
                domain_initial_dot = v.startswith('.')
            else:
                domain_initial_dot = None
            v = long(QtCookie.expirationDate().toTime_t())
            # Long type boundary on 32bit platfroms; avoid ValueError
            expires = 2147483647 if v > 2147483647 else v
            rest = {}
            discard = False
            return Cookie(
                0,
                name,
                value,
                port,
                port_specified,
                domain,
                domain_specified,
                domain_initial_dot,
                path,
                path_specified,
                secure,
                expires,
                discard,
                None,
                None,
                rest,
            )

        if cookie_storage.__class__.__name__ == 'str':
            cj = LWPCookieJar(cookie_storage)
            toPyCookieJar(self.cookie_jar, cj)
            cj.save()
        elif cookie_storage.__class__.__name__.endswith('CookieJar'):
            toPyCookieJar(self.cookie_jar, cookie_storage)
        else:
            raise ValueError('unsupported cookie_storage type.')