Skip to content
Myr

Merge remote-tracking branch 'upstream/develop' into develop

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Idan Gazit · committed by Idan Gazit · parents 324336e, 53d60ca · Browse files · 13 files+563 added−135 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+563 added−135 removed

  • tests:+202 added−8 removed
  • other:+361 added−127 removed

13 files+563 added−135 removed

modified:docs/user/quickstart.rst+2 added-2 removed
300 unmodified lines
301302 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'303 >>> r = requests.get(url)304305 >>> print r.cookies306 {'requests-is': 'awesome'}305 >>> r.cookies['requests-is']306 'awesome'307308To send your own cookies to the server, you can use the ``cookies``309parameter::310
122 unmodified lines
modified:requests/compat.py+2 added-2 removed
81 unmodified lines
82 from urllib import quote, unquote, urlencode83 from urlparse import urlparse, urlunparse, urljoin, urlsplit84 from urllib2 import parse_http_list85 import cookielib86 from .packages.oreos.monkeys import SimpleCookie86 from Cookie import Morsel87 from StringIO import StringIO8889 bytes = str90 str = unicode
4 unmodified lines
95elif is_py3:96 from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote97 from urllib.request import parse_http_list98 from http import cookiejar as cookielib99 from http.cookies import SimpleCookie99 from http.cookies import Morsel100 from io import StringIO101102 str = str103 bytes = bytes
2 unmodified lines
added:requests/cookies.py+264 added
1"""2Compatibility code to be able to use `cookielib.CookieJar` with requests.34requests.utils imports from here, so be careful with imports.5"""67import collections8from .compat import cookielib, urlparse, Morsel910try:11 import threading12 # grr, pyflakes: this fixes "redefinition of unused 'threading'"13 threading14except ImportError:15 import dummy_threading as threading1617class MockRequest(object):18 """Wraps a `requests.Request` to mimic a `urllib2.Request`.1920 The code in `cookielib.CookieJar` expects this interface in order to correctly21 manage cookie policies, i.e., determine whether a cookie can be set, given the22 domains of the request and the cookie.2324 The original request object is read-only. The client is responsible for collecting25 the new headers via `get_new_headers()` and interpreting them appropriately. You26 probably want `get_cookie_header`, defined below.27 """2829 def __init__(self, request):30 self._r = request31 self._new_headers = {}3233 def get_type(self):34 return urlparse(self._r.full_url).scheme3536 def get_host(self):37 return urlparse(self._r.full_url).netloc3839 def get_origin_req_host(self):40 if self._r.response.history:41 r = self._r.response.history[0]42 return urlparse(r).netloc43 else:44 return self.get_host()4546 def get_full_url(self):47 return self._r.full_url4849 def is_unverifiable(self):50 # unverifiable == redirected51 return bool(self._r.response.history)5253 def has_header(self, name):54 return name in self._r.headers or name in self._new_headers5556 def get_header(self, name, default=None):57 return self._r.headers.get(name, self._new_headers.get(name, default))5859 def add_header(self, key, val):60 """cookielib has no legitimate use for this method; add it back if you find one."""61 raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")6263 def add_unredirected_header(self, name, value):64 self._new_headers[name] = value6566 def get_new_headers(self):67 return self._new_headers6869class MockResponse(object):70 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.7172 ...what? Basically, expose the parsed HTTP headers from the server response73 the way `cookielib` expects to see them.74 """7576 def __init__(self, headers):77 """Make a MockResponse for `cookielib` to read.7879 :param headers: a httplib.HTTPMessage or analogous carrying the headers80 """81 self._headers = headers8283 def info(self):84 return self._headers8586 def getheaders(self, name):87 self._headers.getheaders(name)8889def extract_cookies_to_jar(jar, request, response):90 """Extract the cookies from the response into a CookieJar.9192 :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)93 :param request: our own requests.Request object94 :param response: urllib3.HTTPResponse object95 """96 # the _original_response field is the wrapped httplib.HTTPResponse object,97 # and in safe mode, it may be None if the request didn't actually complete.98 # in that case, just skip the cookie extraction.99 if response._original_response is not None:100 req = MockRequest(request)101 # pull out the HTTPMessage with the headers and put it in the mock:102 res = MockResponse(response._original_response.msg)103 jar.extract_cookies(res, req)104105def get_cookie_header(jar, request):106 """Produce an appropriate Cookie header string to be sent with `request`, or None."""107 r = MockRequest(request)108 jar.add_cookie_header(r)109 return r.get_new_headers().get('Cookie')110111def remove_cookie_by_name(cookiejar, name, domain=None, path=None):112 """Unsets a cookie by name, by default over all domains and paths.113114 Wraps CookieJar.clear(), is O(n).115 """116 clearables = []117 for cookie in cookiejar:118 if cookie.name == name:119 if domain is None or domain == cookie.domain:120 if path is None or path == cookie.path:121 clearables.append((cookie.domain, cookie.path, cookie.name))122123 for domain, path, name in clearables:124 cookiejar.clear(domain, path, name)125126class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):127 """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface.128129 This is the CookieJar we create by default for requests and sessions that130 don't specify one, since some clients may expect response.cookies and131 session.cookies to support dict operations.132133 Don't use the dict interface internally; it's just for compatibility with134 with external client code. All `requests` code should work out of the box135 with externally provided instances of CookieJar, e.g., LWPCookieJar and136 FileCookieJar.137138 Caution: dictionary operations that are normally O(1) may be O(n).139140 Unlike a regular CookieJar, this class is pickleable.141 """142143 def get(self, name, domain=None, path=None, default=None):144 try:145 return self._find(name, domain, path)146 except KeyError:147 return default148149 def set(self, name, value, **kwargs):150 # support client code that unsets cookies by assignment of a None value:151 if value is None:152 remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))153 return154155 if isinstance(value, Morsel):156 c = morsel_to_cookie(value)157 else:158 c = create_cookie(name, value, **kwargs)159 self.set_cookie(c)160 return c161162 def __getitem__(self, name):163 return self._find(name)164165 def __setitem__(self, name, value):166 self.set(name, value)167168 def __delitem__(self, name):169 remove_cookie_by_name(self, name)170171 def _find(self, name, domain=None, path=None):172 for cookie in iter(self):173 if cookie.name == name:174 if domain is None or cookie.domain == domain:175 if path is None or cookie.path == path:176 return cookie.value177178 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))179180 def __getstate__(self):181 state = self.__dict__.copy()182 # remove the unpickleable RLock object183 state.pop('_cookies_lock')184 return state185186 def __setstate__(self, state):187 self.__dict__.update(state)188 if '_cookies_lock' not in self.__dict__:189 self._cookies_lock = threading.RLock()190191 def copy(self):192 """We're probably better off forbidding this."""193 raise NotImplementedError194195def create_cookie(name, value, **kwargs):196 """Make a cookie from underspecified parameters.197198 By default, the pair of `name` and `value` will be set for the domain ''199 and sent on every request (this is sometimes called a "supercookie").200 """201 result = dict(202 version=0,203 name=name,204 value=value,205 port=None,206 domain='',207 path='/',208 secure=False,209 expires=None,210 discard=True,211 comment=None,212 comment_url=None,213 rest={'HttpOnly': None},214 rfc2109=False,215 )216217 badargs = set(kwargs) - set(result)218 if badargs:219 err = 'create_cookie() got unexpected keyword arguments: %s'220 raise TypeError(err % list(badargs))221222 result.update(kwargs)223 result['port_specified'] = bool(result['port'])224 result['domain_specified'] = bool(result['domain'])225 result['domain_initial_dot'] = result['domain'].startswith('.')226 result['path_specified'] = bool(result['path'])227228 return cookielib.Cookie(**result)229230def morsel_to_cookie(morsel):231 """Convert a Morsel object into a Cookie containing the one k/v pair."""232 c = create_cookie(233 name=morsel.key,234 value=morsel.value,235 version=morsel['version'] or 0,236 port=None,237 port_specified=False,238 domain=morsel['domain'],239 domain_specified=bool(morsel['domain']),240 domain_initial_dot=morsel['domain'].startswith('.'),241 path=morsel['path'],242 path_specified=bool(morsel['path']),243 secure=bool(morsel['secure']),244 expires=morsel['max-age'] or morsel['expires'],245 discard=False,246 comment=morsel['comment'],247 comment_url=bool(morsel['comment']),248 rest={'HttpOnly': morsel['httponly']},249 rfc2109=False,250 )251 return c252253def cookiejar_from_dict(cookie_dict, cookiejar=None):254 """Returns a CookieJar from a key/value dictionary.255256 :param cookie_dict: Dict of key/values to insert into CookieJar.257 """258 if cookiejar is None:259 cookiejar = RequestsCookieJar()260261 if cookie_dict is not None:262 for name in cookie_dict:263 cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))264 return cookiejar
modified:requests/models.py+25 added-32 removed
13 unmodified lines
14from .structures import CaseInsensitiveDict15from .status_codes import codes1617from .auth import HTTPBasicAuth, HTTPProxyAuth18from .cookies import cookiejar_from_dict, extract_cookies_to_jar, get_cookie_header19from .packages.urllib3.response import HTTPResponse20from .packages.urllib3.exceptions import MaxRetryError, LocationParseError21from .packages.urllib3.exceptions import SSLError as _SSLError22from .packages.urllib3.exceptions import HTTPError as _HTTPError
4 unmodified lines
27 ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,28 URLRequired, SSLError, MissingSchema, InvalidSchema, InvalidURL)29from .utils import (30 get_encoding_from_headers, stream_untransfer, guess_filename, requote_uri,30 dict_from_string, stream_decode_response_unicode, get_netrc_auth,31 stream_decode_response_unicode, get_netrc_auth,32 DEFAULT_CA_BUNDLE_PATH)33from .compat import (33 urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,34 SimpleCookie, is_py2)34 cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,35 is_py2)3637# Import chardet if it is available.38try:39 import chardet
86 unmodified lines
126 #: Authentication tuple or object to attach to :class:`Request <Request>`.127 self.auth = auth128129 #: CookieJar to attach to :class:`Request <Request>`.129 self.cookies = dict(cookies or [])130 if isinstance(cookies, cookielib.CookieJar):131 self.cookies = cookies132 else:133 self.cookies = cookiejar_from_dict(cookies)134135 #: True if Request has been sent.136 self.sent = False137
58 unmodified lines
196197 # Set encoding.198 response.encoding = get_encoding_from_headers(response.headers)199196 # Start off with our local cookies.197 cookies = self.cookies or dict()198200 # Add new cookies from the server.200 if 'set-cookie' in response.headers:201 cookie_header = response.headers['set-cookie']202 cookies = dict_from_string(cookie_header)201 extract_cookies_to_jar(self.cookies, self, resp)202203 # Save cookies in Response.205 response.cookies = cookies204 response.cookies = self.cookies205206 # No exceptions were harmed in the making of this request.207 response.error = getattr(resp, 'error', None)208
9 unmodified lines
218 history = []219220 r = build(resp)221223 self.cookies.update(r.cookies)224222 if r.status_code in REDIRECT_STATI and not self.redirect:223224 while (('location' in r.headers) and225 ((r.status_code is codes.see_other) or (self.allow_redirects))):
69 unmodified lines
295 )296297 request.send()298 r = request.response302 self.cookies.update(r.cookies)299300 r.history = history301302 self.response = r303 self.response.request = self308 self.response.cookies.update(self.cookies)304305 @staticmethod306 def _encode_params(data):307 """Encode parameters in a piece of data.
251 unmodified lines
559 conn.cert_file = self.cert560561 if not self.sent or anyway:562568 if self.cookies:569570 # Skip if 'cookie' header is explicitly set.571 if 'cookie' not in self.headers:572573 # Simple cookie with our dict.574 c = SimpleCookie()575 for (k, v) in list(self.cookies.items()):576 c[k] = v577578 # Turn it into a header.579 cookie_header = c.output(header='', sep='; ').strip()580581 # Attach Cookie header to request.563 # Skip if 'cookie' header is explicitly set.564 if 'cookie' not in self.headers:565 cookie_header = get_cookie_header(self.cookies, self)566 if cookie_header is not None:567 self.headers['Cookie'] = cookie_header568569 # Pre-request hook.570 r = dispatch_hook('pre_request', self.hooks, self)
36 unmodified lines
607 r.error = e608 else:609 raise610611 # build_response can throw TooManyRedirects612 try:626 self._build_response(r)613 self._build_response(r)614 except RequestException as e:615 if self.config.get('safe_mode', False):616 # In safe mode, catch the exception617 self.response.error = e618 else:619 raise620621 # Response manipulation hook.622 self.response = dispatch_hook('response', self.hooks, self.response)623
51 unmodified lines
675676 #: The :class:`Request <Request>` that created the Response.677 self.request = None678686 #: A dictionary of Cookies the server sent back.687 self.cookies = {}679 #: A CookieJar of Cookies the server sent back.680 self.cookies = None681682 #: Dictionary of configurations for this request.683 self.config = {}684
153 unmodified lines
modified:requests/sessions.py+31 added-10 removed
7 unmodified lines
8requests (cookies, auth, proxies).910"""1112from .compat import cookielib13from .cookies import cookiejar_from_dict, remove_cookie_by_name14from .defaults import defaults15from .models import Request16from .hooks import dispatch_hook17from .utils import header_expand18from .packages.urllib3.poolmanager import PoolManager191820def merge_kwargs(local_kwarg, default_kwarg):21 """Merges kwarg dictionaries.2223 If a local key in the dictionary is set to None, it will be removed.
45 unmodified lines
69 verify=True,70 cert=None):7172 self.headers = headers or {}72 self.cookies = cookies or {}73 self.auth = auth74 self.timeout = timeout75 self.proxies = proxies or {}76 self.hooks = hooks or {}
8 unmodified lines
8586 self.init_poolmanager()8788 # Set up a CookieJar to be used by default89 if isinstance(cookies, cookielib.CookieJar):89 self.cookies = {}90 self.cookies = cookies91 else:92 self.cookies = cookiejar_from_dict(cookies)9391 # Add passed cookies in.92 if cookies is not None:93 self.cookies.update(cookies)9494 def init_poolmanager(self):95 self.poolmanager = PoolManager(96 num_pools=self.config.get('pool_connections'),97 maxsize=self.config.get('pool_maxsize')
48 unmodified lines
146147 method = str(method).upper()148149 # Default empty dicts for dict params.151 cookies = {} if cookies is None else cookies150 data = {} if data is None else data151 files = {} if files is None else files152 headers = {} if headers is None else headers153 params = {} if params is None else params
28 unmodified lines
182 cert=cert,183 _poolmanager=self.poolmanager184 )185186 # merge session cookies into passed-in ones187 dead_cookies = None188 # passed-in cookies must become a CookieJar:189 if not isinstance(cookies, cookielib.CookieJar):190 args['cookies'] = cookiejar_from_dict(cookies)191 # support unsetting cookies that have been passed in with None values192 # this is only meaningful when `cookies` is a dict ---193 # for a real CookieJar, the client should use session.cookies.clear()194 if cookies is not None:195 dead_cookies = [name for name in cookies if cookies[name] is None]196 # merge the session's cookies into the passed-in cookies:197 for cookie in self.cookies:198 args['cookies'].set_cookie(cookie)199 # remove the unset cookies from the jar we'll be using with the current request200 # (but not from the session's own store of cookies):201 if dead_cookies is not None:202 for name in dead_cookies:203 remove_cookie_by_name(args['cookies'], name)204205 # Merge local kwargs with session kwargs.206 for attr in self.__attrs__:207 # we already merged cookies:208 if attr == 'cookies':209 continue210211 session_val = getattr(self, attr, None)212 local_val = args.get(attr)192213 args[attr] = merge_kwargs(local_val, session_val)214215 # Arguments manipulation hook.216 args = dispatch_hook('args', args['hooks'], args)
11 unmodified lines
228 # Send the HTTP Request.229 r.send(prefetch=prefetch)230231 # Send any cookies back up the to the session.212 self.cookies.update(r.response.cookies)232 for cookie in r.response.cookies:233 self.cookies.set_cookie(cookie)234235 # Return the response.236 return r.response237
90 unmodified lines
modified:requests/utils.py+6 added-62 removed
16 unmodified lines
17import zlib18from netrc import netrc, NetrcParseError1920from .compat import parse_http_list as _parse_list_header21from .compat import quote, cookielib, SimpleCookie, is_py2, urlparse21from .compat import quote, is_py2, urlparse22from .compat import basestring, bytes, str23from .cookies import RequestsCookieJar, cookiejar_from_dict2425_hush_pyflakes = (RequestsCookieJar,)2627CERTIFI_BUNDLE_PATH = None28try:29 # see if requests's own CA certificate bundle is installed30 import certifi
68 unmodified lines
99 except AttributeError:100 pass101102100101def dict_from_string(s):102 """Returns a MultiDict with Cookies."""103104 cookies = dict()105106 try:107 c = SimpleCookie()108 c.load(s)109110 for k, v in list(c.items()):111 cookies.update({k: v.value})112 # This stuff is not to be trusted.113 except Exception:114 pass115116 return cookies117118103def guess_filename(obj):104 """Tries to guess the filename of the given object."""105 name = getattr(obj, 'name', None)106 if name and name[0] != '<' and name[-1] != '>':
166 unmodified lines
273274 return cookie_dict275276293def cookiejar_from_dict(cookie_dict):294 """Returns a CookieJar from a key/value dictionary.295296 :param cookie_dict: Dict of key/values to insert into CookieJar.297 """298299 # return cookiejar if one was passed in300 if isinstance(cookie_dict, cookielib.CookieJar):301 return cookie_dict302303 # create cookiejar304 cj = cookielib.CookieJar()305306 cj = add_dict_to_cookiejar(cj, cookie_dict)307308 return cj309310277def add_dict_to_cookiejar(cj, cookie_dict):278 """Returns a CookieJar from a key/value dictionary.279280 :param cj: CookieJar to insert cookies into.281 :param cookie_dict: Dict of key/values to insert into CookieJar.282 """283318 for k, v in list(cookie_dict.items()):319320 cookie = cookielib.Cookie(321 version=0,322 name=k,323 value=v,324 port=None,325 port_specified=False,326 domain='',327 domain_specified=False,328 domain_initial_dot=False,329 path='/',330 path_specified=True,331 secure=False,332 expires=None,333 discard=True,334 comment=None,335 comment_url=None,336 rest={'HttpOnly': None},337 rfc2109=False338 )339340 # add cookie to cookiejar284 cj2 = cookiejar_from_dict(cookie_dict)285 for cookie in cj2:286 cj.set_cookie(cookie)342287 return cj288289290def get_encodings_from_content(content):
158 unmodified lines
added:tests/test_cookies.py+166 added
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import sys5import json6import os7import tempfile8import unittest910# Path hack.11sys.path.insert(0, os.path.abspath('..'))12import requests13from requests.compat import cookielib1415# More hacks16sys.path.append('.')17from test_requests import httpbin, TestBaseMixin1819class CookieTests(TestBaseMixin, unittest.TestCase):2021 def test_cookies_from_response(self):22 """Basic test that we correctly parse received cookies in the Response object."""23 r = requests.get(httpbin('cookies', 'set', 'myname', 'myvalue'))2425 # test deprecated dictionary interface26 self.assertEqual(r.cookies['myname'], 'myvalue')27 # test CookieJar interface28 jar = r.cookies29 self.assertEqual(len(jar), 1)30 cookie_from_jar = list(jar)[0]31 self.assertCookieHas(cookie_from_jar, name='myname', value='myvalue')3233 q = requests.get(httpbin('cookies'), cookies=jar)34 self.assertEqual(json.loads(q.text)['cookies'], {'myname': 'myvalue'})3536 def test_crossdomain_cookies(self):37 """Cookies should not be sent to domains they didn't originate from."""38 r = requests.get("http://github.com")39 c = r.cookies40 # github should send us cookies41 self.assertGreaterEqual(len(c), 1)4243 # github cookies should not be sent to httpbin.org:44 r2 = requests.get(httpbin('cookies'), cookies=c)45 self.assertEqual(json.loads(r2.text)['cookies'], {})4647 # let's do this again using the session object48 s = requests.session()49 s.get("http://github.com")50 self.assertGreaterEqual(len(s.cookies), 1)51 r = s.get(httpbin('cookies'))52 self.assertEqual(json.loads(r.text)['cookies'], {})53 # we can set a cookie and get exactly that same-domain cookie back:54 r = s.get(httpbin('cookies', 'set', 'myname', 'myvalue'))55 self.assertEqual(json.loads(r.text)['cookies'], {'myname': 'myvalue'})5657 def test_overwrite(self):58 """Cookies should get overwritten when appropriate."""59 r = requests.get(httpbin('cookies', 'set', 'shimon', 'yochai'))60 cookies = r.cookies61 requests.get(httpbin('cookies', 'set', 'elazar', 'shimon'), cookies=cookies)62 r = requests.get(httpbin('cookies'), cookies=cookies)63 self.assertEqual(json.loads(r.text)['cookies'],64 {'shimon': 'yochai', 'elazar': 'shimon'})65 # overwrite the value of 'shimon'66 r = requests.get(httpbin('cookies', 'set', 'shimon', 'gamaliel'), cookies=cookies)67 self.assertEqual(len(cookies), 2)68 r = requests.get(httpbin('cookies'), cookies=cookies)69 self.assertEqual(json.loads(r.text)['cookies'],70 {'shimon': 'gamaliel', 'elazar': 'shimon'})7172 def test_redirects(self):73 """Test that cookies set by a 302 page are correctly processed."""74 r = requests.get(httpbin('cookies', 'set', 'redirects', 'work'))75 self.assertEqual(r.history[0].status_code, 302)76 expected_cookies = {'redirects': 'work'}77 self.assertEqual(json.loads(r.text)['cookies'], expected_cookies)7879 r2 = requests.get(httpbin('cookies', 'set', 'very', 'well'), cookies=r.cookies)80 expected_cookies = {'redirects': 'work', 'very': 'well'}81 self.assertEqual(json.loads(r2.text)['cookies'], expected_cookies)82 self.assertIs(r.cookies, r2.cookies)8384 def test_none_cookie(self):85 """Regression test: don't send a Cookie header with a string value of 'None'!"""86 page = json.loads(requests.get(httpbin('headers')).text)87 self.assertNotIn('Cookie', page['headers'])8889class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):90 """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""9192 COOKIEJAR_CLASS = cookielib.LWPCookieJar9394 def setUp(self):95 # blank the file96 self.cookiejar_file = tempfile.NamedTemporaryFile()97 self.cookiejar_filename = self.cookiejar_file.name98 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)99 cookiejar.save()100101 def tearDown(self):102 try:103 self.cookiejar_file.close()104 except OSError:105 pass106107 def test_cookiejar_persistence(self):108 """Test that we can save cookies to a FileCookieJar."""109 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)110 cookiejar.load()111 # initially should be blank112 self.assertEqual(len(cookiejar), 0)113114 response = requests.get(httpbin('cookies', 'set', 'key', 'value'), cookies=cookiejar)115 self.assertEqual(len(cookiejar), 1)116 cookie = list(cookiejar)[0]117 self.assertEqual(json.loads(response.text)['cookies'], {'key': 'value'})118 self.assertCookieHas(cookie, name='key', value='value')119120 # save and reload the cookies from the file:121 cookiejar.save(ignore_discard=True)122 cookiejar_2 = self.COOKIEJAR_CLASS(self.cookiejar_filename)123 cookiejar_2.load(ignore_discard=True)124 self.assertEqual(len(cookiejar_2), 1)125 cookie_2 = list(cookiejar_2)[0]126 # this cookie should have been saved with the correct domain restriction:127 self.assertCookieHas(cookie_2, name='key', value='value',128 domain='httpbin.org', path='/')129130 # httpbin sets session cookies, so if we don't ignore the discard attribute,131 # there should be no cookie:132 cookiejar_3 = self.COOKIEJAR_CLASS(self.cookiejar_filename)133 cookiejar_3.load()134 self.assertEqual(len(cookiejar_3), 0)135136 def test_crossdomain(self):137 """Test persistence of the domains associated with the cookies."""138 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)139 cookiejar.load()140 self.assertEqual(len(cookiejar), 0)141142 # github sets a cookie143 requests.get("http://github.com", cookies=cookiejar)144 num_github_cookies = len(cookiejar)145 self.assertGreaterEqual(num_github_cookies, 1)146 # httpbin sets another147 requests.get(httpbin('cookies', 'set', 'key', 'value'), cookies=cookiejar)148 num_total_cookies = len(cookiejar)149 self.assertGreaterEqual(num_total_cookies, 2)150 self.assertGreater(num_total_cookies, num_github_cookies)151152 # save and load153 cookiejar.save(ignore_discard=True)154 cookiejar_2 = self.COOKIEJAR_CLASS(self.cookiejar_filename)155 cookiejar_2.load(ignore_discard=True)156 self.assertEqual(len(cookiejar_2), num_total_cookies)157 r = requests.get(httpbin('cookies'), cookies=cookiejar_2)158 self.assertEqual(json.loads(r.text)['cookies'], {'key': 'value'})159160class MozCookieJarTest(LWPCookieJarTest):161 """Same test, but substitute MozillaCookieJar."""162163 COOKIEJAR_CLASS = cookielib.MozillaCookieJar164165if __name__ == '__main__':166 unittest.main()
modified:tests/test_requests_async.py-1 removed
10 unmodified lines
11import select12has_poll = hasattr(select, "poll")1314from requests import async15import envoy1516sys.path.append('.')17from test_requests import httpbin, RequestsTestSuite, SERVICES18
49 unmodified lines
modified:tests/test_requests_ext.py+19 added
102 unmodified lines
103 'News/~3/BQtUJRJeZlo/deal_view_investment.' +104 'php')105 assert r.ok106107 def test_cookies_on_redirects(self):108 """Test interaction between cookie handling and redirection."""109 # get a cookie for tinyurl.com ONLY110 s = requests.session()111 s.get(url='http://tinyurl.com/preview.php?disable=1')112 # we should have set a cookie for tinyurl: preview=0113 self.assertIn('preview', s.cookies)114 self.assertEqual(s.cookies['preview'], '0')115 self.assertEqual(list(s.cookies)[0].name, 'preview')116 self.assertEqual(list(s.cookies)[0].domain, 'tinyurl.com')117118 # get cookies on another domain119 r2 = s.get(url='http://httpbin.org/cookies')120 # the cookie is not there121 self.assertNotIn('preview', json.loads(r2.text)['cookies'])122123 # this redirects to another domain, httpbin.org124 # cookies of the first domain should NOT be sent to the next one125 r3 = s.get(url='http://tinyurl.com/7zp3jnr')126 assert r3.url == 'http://httpbin.org/cookies'127 self.assertNotIn('preview', json.loads(r2.text)['cookies'])128129if __name__ == '__main__':130 unittest.main()131
modified:tests/test_requests.py+17 added-7 removed
8 unmodified lines
9sys.path.insert(0, os.path.abspath('..'))1011import json12import os13import sys13import unittest14import pickle1516import requests
33 unmodified lines
50 # c = envoy.connect('httpbin %s' % (PORT))51 # time.sleep(1)52 _httpbin = True5354class TestBaseMixin(object):5556 def assertCookieHas(self, cookie, **kwargs):57 """Assert that a cookie has various specified properties."""58 for attr, expected_value in kwargs.items():59 message = 'Failed comparison for %s' % (attr,)60 self.assertEqual(getattr(cookie, attr), expected_value, message)6156class RequestsTestSuite(TestSetup, unittest.TestCase):62class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):63 """Requests test cases."""6465 def test_entry_points(self):66
570 unmodified lines
637 r = get(httpbin('cookies'), session=s)638639 # Those cookies persist transparently.640 c = json.loads(r.text).get('cookies')635 assert c == _c641 self.assertEqual(c, _c)642643 # Double check.644 r = get(httpbin('cookies'), cookies={}, session=s)645 c = json.loads(r.text).get('cookies')640 assert c == _c646 self.assertEqual(c, _c)647648 # Remove a cookie by setting it's value to None.649 r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)650 c = json.loads(r.text).get('cookies')651 del _c['bessie']646 assert c == _c652 self.assertEqual(c, _c)653654 # Test session-level cookies.655 s = requests.session(cookies=_c)656 r = get(httpbin('cookies'), session=s)657 c = json.loads(r.text).get('cookies')652 assert c == _c658 self.assertEqual(c, _c)659660 # Have the server set a cookie.661 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)662 c = json.loads(r.text).get('cookies')
40 unmodified lines
703704 ds = pickle.loads(pickle.dumps(s))705706 self.assertEqual(s.headers, ds.headers)701 self.assertEqual(s.cookies, ds.cookies)707 self.assertEqual(s.auth, ds.auth)708709 # Cookie doesn't have a good __eq__, so verify manually:710 self.assertEqual(len(ds.cookies), 1)711 for cookie in ds.cookies:712 self.assertCookieHas(cookie, name='a-cookie', value='cookie-value')713714 def test_unpickled_session_requests(self):715 s = requests.session()716 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)717 c = json.loads(r.text).get('cookies')
134 unmodified lines
modified:.gitignore+4 added-4 removed
1MANIFEST2coverage.xml3nosetests.xml4pylint.txt5*.pyc6docs/_build5toy.py8.gitignore6junit-report.xml10requests.egg-info/7requests.egg-info/8docs/_build9*.pyc10*.swp
modified:AUTHORS.rst+1 added
94 unmodified lines
95- Michael Kelly96- Michael Newman <newmaniese@gmail.com>97- Jonty Wareing <jonty@jonty.co.uk>98- Shivaram Lingamneni99- Miguel Turner
modified:setup.py+26 added-15 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-24import os3"""4distutils/setuptools install script. See inline comments for packaging documentation.5"""67import sys89import requests7from requests.compat import is_py3, is_py210from requests.compat import is_py31112try:13 from setuptools import setup14except ImportError:15 from distutils.core import setup16141517if sys.argv[-1] == 'publish':18 os.system('python setup.py sdist upload')19 sys.exit()2020if sys.argv[-1] == 'test':21 os.system('python tests/test_requests.py')22 sys.exit()2324required = ['certifi>=0.0.7']21packages = [22 'requests',23 'requests.packages',24 'requests.packages.urllib3',
1 unmodified line
26 'requests.packages.urllib3.packages.ssl_match_hostname',27 'requests.packages.urllib3.packages.mimetools_choose_boundary',28]2930# certifi is a Python package containing a CA certificate bundle for SSL verification.31# On certain supported platforms (e.g., Red Hat / Debian / FreeBSD), Requests can32# use the system CA bundle instead; see `requests.utils` for details.33# If your platform is supported, set `requires` to [] instead:34requires = ['certifi>=0.0.7']3536# chardet is used to optimally guess the encodings of pages that don't declare one.37# At this time, chardet is not a required dependency. However, it's sufficiently38# important that pip/setuptools should install it when it's unavailable.39if is_py3:35 required.append('chardet2')40 chardet_package = 'chardet2'41else:37 required.append('chardet>=1.0.0')38 required.append('oauthlib')39 packages.append('requests.packages.oreos')42 chardet_package = 'chardet>=1.0.0'43requires.append(chardet_package)4445# The async API in requests.async requires the gevent package.46# This is also not a required dependency.47extras_require = {48 'async': ['gevent'],49}5051setup(52 name='requests',53 version=requests.__version__,54 description='Python HTTP for Humans.',
4 unmodified lines
59 url='http://python-requests.org',60 packages=packages,61 package_data={'': ['LICENSE', 'NOTICE']},62 include_package_data=True,53 install_requires=required,63 install_requires=requires,64 extras_require=extras_require,65 license=open("LICENSE").read(),66 classifiers=(67 'Development Status :: 5 - Production/Stable',68 'Intended Audience :: Developers',
10 unmodified lines