Python requests 模块,cookies() 实例源码

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

项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_as_dict_keeps_items(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert d1['some_cookie'] == 'some_value'
        assert d2['some_cookie'] == 'some_value'
        assert d3['some_cookie1'] == 'some_value1'
项目:meican    作者:wujiyu115    | 项目源码 | 文件源码
def load_cookies(session, filename):
    if not os.path.isfile(filename):
        return False

    with open(filename) as f:
        try:
            cookies = pickle.load(f)
            if cookies:
                jar = requests.cookies.RequestsCookieJar()
                jar._cookies = cookies
                session.cookies = jar
                return True
            else:
                return False
        except EOFError:
            return False
项目:data007    作者:mobishift2011    | 项目源码 | 文件源码
def get_json(api, data):
    if session.cookies.get('_m_h5_tk', '') == '':
        setup_token()
    url = get_request_url(api, data)

    text = retry(3, session.get, url, timeout=30).text

    if u'????' in text or u'????' in text:
        setup_token()
        return get_json(api, data)
    elif u'?????' in text or u'ID??' in text or u'???????' in text or u'?????' in text:
        return {'error': 'not found'}
    elif u'??????' in text:
        raise NotFoundError("Taobao Api Error")
    else:
        resp = json.loads(text.strip()[6:-1])
        if not resp['ret'][0].startswith('SUCCESS'):
            raise ValueError('Unknown API Failure: {}'.format(text.encode('utf-8')))
        else:
            return resp
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_as_dict_keeps_len(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert len(jar) == 2
        assert len(d1) == 2
        assert len(d2) == 2
        assert len(d3) == 2
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_as_dict_keeps_items(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert d1['some_cookie'] == 'some_value'
        assert d2['some_cookie'] == 'some_value'
        assert d3['some_cookie1'] == 'some_value1'
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_parameters(self):
        key = 'some_cookie'
        value = 'some_value'
        secure = True
        domain = 'test.com'
        rest = {'HttpOnly': True}

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value, secure=secure, domain=domain, rest=rest)

        assert len(jar) == 1
        assert 'some_cookie' in jar

        cookie = list(jar)[0]
        assert cookie.secure == secure
        assert cookie.domain == domain
        assert cookie._rest['HttpOnly'] == rest['HttpOnly']
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_as_dict_keeps_len(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert len(jar) == 2
        assert len(d1) == 2
        assert len(d2) == 2
        assert len(d3) == 2
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_as_dict_keeps_items(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert d1['some_cookie'] == 'some_value'
        assert d2['some_cookie'] == 'some_value'
        assert d3['some_cookie1'] == 'some_value1'
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_duplicate_names_different_domains(self):
        key = 'some_cookie'
        value = 'some_value'
        domain1 = 'test1.com'
        domain2 = 'test2.com'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value, domain=domain1)
        jar.set(key, value, domain=domain2)
        assert key in jar
        items = jar.items()
        assert len(items) == 2

        # Verify that CookieConflictError is raised if domain is not specified
        with pytest.raises(requests.cookies.CookieConflictError):
            jar.get(key)

        # Verify that CookieConflictError is not raised if domain is specified
        cookie = jar.get(key, domain=domain1)
        assert cookie == value
项目:infrared    作者:redhat-openstack    | 项目源码 | 文件源码
def create_session(self):
        """
        Creates a session and get some details on the machine.
        """
        self.session = requests.Session()
        self.session.auth = self.auth

        # whether verify the SSL certificate or not
        self.session.verify = self.ca_cert or False

        if self.disable_warnings:
            requests.packages.urllib3.disable_warnings()

        if self.web_service == 'rpc':
            self.session.cookies = requests.cookies.cookiejar_from_dict(
                self._xml_rpc_auth())
        else:
            # cookie workaround - consider changing with _get_last_activity()
            self.list_systems(limit=1)

        self.details = self.get_system_details()
项目:itp-energy-forecast-with-enertiv    作者:821760408-sp    | 项目源码 | 文件源码
def login(self):
    try:
      self.session = requests.session()
      self.session.stream = False
      self.session.get(self.login_url, verify=False, timeout=self.timeout)
      self.csrf_token = self.session.cookies['csrftoken']
      login_data = dict(username=self.server_user, password=self.server_password, csrfmiddlewaretoken=self.csrf_token)
      headers = {"X-CSRFToken": self.csrf_token, "Referer": "%s://%s" % (self.server_protocol, self.server_host)}
      response = self.session.post(self.login_url, data=login_data, headers=headers, timeout=self.timeout, verify=False)
      if (response.status_code != 200):
        logger.info("login result %s %s" % (response.status_code, response.text))
    except Timeout as e:
      logger.warning('Login for %s timed out: %s' % (self.login_url, e))
      raise e
    except Exception as e:
      logger.error(e)
      raise e
    return response
项目:Codeforces-Sublime-Plugin    作者:karunk    | 项目源码 | 文件源码
def test_cookie_as_dict_keeps_len(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert len(jar) == 2
        assert len(d1) == 2
        assert len(d2) == 2
        assert len(d3) == 2
项目:Codeforces-Sublime-Plugin    作者:karunk    | 项目源码 | 文件源码
def test_cookie_as_dict_keeps_items(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert d1['some_cookie'] == 'some_value'
        assert d2['some_cookie'] == 'some_value'
        assert d3['some_cookie1'] == 'some_value1'
项目:trip    作者:littlecodersh    | 项目源码 | 文件源码
def __init__(self):
        self.headers = default_headers()
        self.auth = None
        self.proxies = {}
        self.hooks = default_hooks()
        self.params = {}
        self.stream = False
        self.verify = True
        self.cert = None
        self.max_redirects = DEFAULT_REDIRECT_LIMIT
        self.trust_env = True
        self.cookies = cookiejar_from_dict({})
        self.adapter = HTTPAdapter()
项目:trip    作者:littlecodersh    | 项目源码 | 文件源码
def prepare_request(self, request):
        cookies = request.cookies or {}

        # Bootstrap CookieJar.
        if not isinstance(cookies, cookielib.CookieJar):
            cookies = cookiejar_from_dict(cookies)

        # Merge with session cookies
        merged_cookies = merge_cookies(
            merge_cookies(RequestsCookieJar(), self.cookies), cookies)

        # Set environment's basic authentication if not explicitly set.
        # auth = request.auth
        # if self.trust_env and not auth and not self.auth:
        #     auth = get_netrc_auth(request.url)

        p = PreparedRequest()
        p.prepare(
            method=request.method.upper(),
            url=request.url,
            files=request.files,
            data=request.data,
            json=request.json,
            headers=merge_setting(request.headers,
                self.headers, dict_class=CaseInsensitiveDict),
            params=merge_setting(request.params, self.params),
            auth=merge_setting(request.auth, self.auth),
            cookies=merged_cookies,
            hooks=merge_hooks(request.hooks, self.hooks),
        )
        return p
项目:trip    作者:littlecodersh    | 项目源码 | 文件源码
def request(self, method, url,
            params=None, data=None, headers=None, cookies=None, files=None,
            auth=None, timeout=None, allow_redirects=True, proxies=None,
            hooks=None, stream=None, verify=None, cert=None, json=None):

        req = Request(
            method=method.upper(),
            url=url,
            headers=headers,
            files=files,
            data=data or {},
            json=json,
            params=params or {},
            auth=auth,
            cookies=cookies,
            hooks=hooks,
        )
        request = self.prepare_request(req)

        proxies = proxies or {}

        settings = self.merge_environment_settings(
            request.url, proxies, stream, verify, cert
        )

        # Send the request.
        send_kwargs = {
            'timeout': timeout,
            'allow_redirects': allow_redirects,
        }
        send_kwargs.update(settings)

        return self.send(request, **send_kwargs)
项目:ynm3k    作者:socrateslee    | 项目源码 | 文件源码
def get_session(self):
        if not self.sess:
            self.sess = requests.Session()
        self.sess.cookies = cookiejar_from_dict({})
        return self.sess
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def __init__(self, path, *args, **kwargs):
        super(Session, self).__init__(*args, **kwargs)
        self._path = path
        self['headers'] = {}
        self['cookies'] = {}
        self['auth'] = {
            'type': None,
            'username': None,
            'password': None
        }
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def cookies(self):
        jar = RequestsCookieJar()
        for name, cookie_dict in self['cookies'].items():
            jar.set_cookie(create_cookie(
                name, cookie_dict.pop('value'), **cookie_dict))
        jar.clear_expired_cookies()
        return jar
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def cookies(self, jar):
        """
        :type jar: CookieJar
        """
        # http://docs.python.org/2/library/cookielib.html#cookie-objects
        stored_attrs = ['value', 'path', 'secure', 'expires']
        self['cookies'] = {}
        for cookie in jar:
            self['cookies'][cookie.name] = dict(
                (attname, getattr(cookie, attname))
                for attname in stored_attrs
            )
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_set_cookie_on_301(self, httpbin):
        s = requests.session()
        url = httpbin('cookies/set?foo=bar')
        s.get(url)
        assert s.cookies['foo'] == 'bar'
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_sent_on_redirect(self, httpbin):
        s = requests.session()
        s.get(httpbin('cookies/set?foo=bar'))
        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')
        assert 'Cookie' in r.json()['headers']
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_removed_on_expire(self, httpbin):
        s = requests.session()
        s.get(httpbin('cookies/set?foo=bar'))
        assert s.cookies['foo'] == 'bar'
        s.get(
            httpbin('response-headers'),
            params={
                'Set-Cookie':
                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'
            }
        )
        assert 'foo' not in s.cookies
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_quote_wrapped(self, httpbin):
        s = requests.session()
        s.get(httpbin('cookies/set?foo="bar:baz"'))
        assert s.cookies['foo'] == '"bar:baz"'
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_persists_via_api(self, httpbin):
        s = requests.session()
        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})
        assert 'foo' in r.request.headers['Cookie']
        assert 'foo' in r.history[0].request.headers['Cookie']
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_request_cookies_not_persisted(self, httpbin):
        s = requests.session()
        s.get(httpbin('cookies'), cookies={'foo': 'baz'})
        # Sending a request with cookies should not add cookies to the session
        assert not s.cookies
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_generic_cookiejar_works(self, httpbin):
        cj = cookielib.CookieJar()
        cookiejar_from_dict({'foo': 'bar'}, cj)
        s = requests.session()
        s.cookies = cj
        r = s.get(httpbin('cookies'))
        # Make sure the cookie was sent
        assert r.json()['cookies']['foo'] == 'bar'
        # Make sure the session cj is still the custom one
        assert s.cookies is cj
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_param_cookiejar_works(self, httpbin):
        cj = cookielib.CookieJar()
        cookiejar_from_dict({'foo': 'bar'}, cj)
        s = requests.session()
        r = s.get(httpbin('cookies'), cookies=cj)
        # Make sure the cookie was sent
        assert r.json()['cookies']['foo'] == 'bar'
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):
        url = httpbin('digest-auth', 'auth', 'user', 'pass')
        auth = HTTPDigestAuth('user', 'pass')
        r = requests.get(url)
        assert r.cookies['fake'] == 'fake_value'

        r = requests.get(url, auth=auth)
        assert r.status_code == 200
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):
        url = httpbin('digest-auth', 'auth', 'user', 'pass')
        auth = HTTPDigestAuth('user', 'pass')
        s = requests.Session()
        s.get(url, auth=auth)
        assert s.cookies['fake'] == 'fake_value'
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_as_dict_keeps_len(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert len(jar) == 2
        assert len(d1) == 2
        assert len(d2) == 2
        assert len(d3) == 2
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_as_dict_keys(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        keys = jar.keys()
        assert keys == list(keys)
        # make sure one can use keys multiple times
        assert list(keys) == list(keys)
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_as_dict_values(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        values = jar.values()
        assert values == list(values)
        # make sure one can use values multiple times
        assert list(values) == list(values)
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_as_dict_items(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        items = jar.items()
        assert items == list(items)
        # make sure one can use items multiple times
        assert list(items) == list(items)
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def test_cookie_duplicate_names_raises_cookie_conflict_error(self):
        key = 'some_cookie'
        value = 'some_value'
        path = 'some_path'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value, path=path)
        jar.set(key, value)
        with pytest.raises(requests.cookies.CookieConflictError):
            jar.get(key)
项目:ruffruffs    作者:di    | 项目源码 | 文件源码
def __init__(self, order_of_redirects):
        self.redirects = order_of_redirects
        self.calls = []
        self.max_redirects = 30
        self.cookies = {}
        self.trust_env = False
项目:apitest    作者:BBVA    | 项目源码 | 文件源码
def __init__(self, *, status_code: int = 200, headers: dict = None, cookies: dict = None,
                 reason: str = None, body: str = None):

        body = body or ""
        status_code = status_code or 200
        headers = headers or {}
        cookies = cookies or {}
        if isinstance(cookies, RequestsCookieJar):
            cookies = dict(cookies)
        reason = reason or "OK"

        assert isinstance(body, str)
        assert isinstance(reason, str)
        assert isinstance(headers, dict)
        assert isinstance(cookies, dict)
        assert isinstance(status_code, int)
        assert isinstance(status_code, int)

        self.body = body
        self.reason = reason
        self.headers = headers
        self.cookies = cookies
        self.status_code = status_code

        self.__content_type_cache = None
        self.__content_body_cache = None
项目:apitest    作者:BBVA    | 项目源码 | 文件源码
def build_from_json(cls, **kwargs):
        o = cls(status_code=kwargs.get("status_code"),
                headers=kwargs.get("headers"),
                body=kwargs.get("body"),
                cookies=kwargs.get("cookies"),
                reason=kwargs.get("reason"))

        return o
项目:apitest    作者:BBVA    | 项目源码 | 文件源码
def request_good(request):
    def _new_fn(url: str, *, method: str = "GET", headers: dict = None, body: str = None):
        # Get the unique signature for the Query
        url_signature = "%s_ok" % make_url_signature(url,
                                                     method=method,
                                                     headers=headers,
                                                     body=body)

        response = request.config.cache.get(url_signature, None)
        # If response is not cached
        if not response:
            # Get and store a GOOD requests
            raw_response = requests.request(url=url, method=method, headers=headers, data=body)

            response = Response(status_code=raw_response.status_code,
                                headers=dict(raw_response.headers),
                                cookies=raw_response.cookies,
                                reason=raw_response.reason,
                                body=raw_response.text)

            request.config.cache.set(url_signature, response.dump_json)
        else:
            # Recover response from cached info
            response = Response.build_from_json(**response)

        return response

    return _new_fn
项目:apitest    作者:BBVA    | 项目源码 | 文件源码
def make_request():
    def _new_fn(url: str, *, method: str = "GET", headers: dict = None, body: str = None):
        raw_response = requests.request(url=url, method=method, headers=headers, data=body)

        return Response(status_code=raw_response.status_code,
                        headers=dict(raw_response.headers),
                        cookies=raw_response.cookies,
                        reason=raw_response.reason,
                        body=raw_response.text)

    return _new_fn
项目:meican    作者:wujiyu115    | 项目源码 | 文件源码
def save_cookies(session, filename):
    with open(filename, 'w') as f:
        f.truncate()
        pickle.dump(session.cookies._cookies, f)
        return True
项目:meican    作者:wujiyu115    | 项目源码 | 文件源码
def has_cookies():
        return os.path.isfile(ConfigUtil.instance().cookies)
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_set_cookie_on_301(self, httpbin):
        s = requests.session()
        url = httpbin('cookies/set?foo=bar')
        s.get(url)
        assert s.cookies['foo'] == 'bar'
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_sent_on_redirect(self, httpbin):
        s = requests.session()
        s.get(httpbin('cookies/set?foo=bar'))
        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')
        assert 'Cookie' in r.json()['headers']
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_removed_on_expire(self, httpbin):
        s = requests.session()
        s.get(httpbin('cookies/set?foo=bar'))
        assert s.cookies['foo'] == 'bar'
        s.get(
            httpbin('response-headers'),
            params={
                'Set-Cookie':
                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'
            }
        )
        assert 'foo' not in s.cookies
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_quote_wrapped(self, httpbin):
        s = requests.session()
        s.get(httpbin('cookies/set?foo="bar:baz"'))
        assert s.cookies['foo'] == '"bar:baz"'
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_cookie_persists_via_api(self, httpbin):
        s = requests.session()
        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})
        assert 'foo' in r.request.headers['Cookie']
        assert 'foo' in r.history[0].request.headers['Cookie']
项目:filegardener    作者:smorin    | 项目源码 | 文件源码
def test_request_cookies_not_persisted(self, httpbin):
        s = requests.session()
        s.get(httpbin('cookies'), cookies={'foo': 'baz'})
        # Sending a request with cookies should not add cookies to the session
        assert not s.cookies