Merge branch 'develop' into key_val_lists
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Conflicts: requests/models.py tests/test_requests.py Remove some of Lukasa's duplication of my efforts in _encode_data.
authored by Ian Cordasco · committed by Ian Cordasco · parents ceec572, cb0fdd8 · Browse files · 27 files·+274 added−105 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
27 files+274 added−105 removed
- tests:+107 added−23 removed
- other:+167 added−82 removed
Provenance
- Commit
e02da89- Tree
2665f21- Author
Ian Cordasco <graffatcolmingov@gmail.com>- Committer
Ian Cordasco <graffatcolmingov@gmail.com>- Parent 1
ceec572- Parent 2
cb0fdd8
27 files changed+274 added−105 removed
modified:docs/_templates/sidebarintro.html+1 added-1 removed
3 unmodified lines456788910111230 unmodified lines3 unmodified lines </a></p>
<p> <iframe src="http://markdotto.github.com/github-buttons/github-btn.html?user=kennethreitz&repo=requests&type=watch&count=true&size=large" <iframe src="http://ghbtns.com/github-btn.html?user=kennethreitz&repo=requests&type=watch&count=true&size=large" allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe></p>
<p>30 unmodified linesmodified:docs/_templates/sidebarlogo.html+1 added-1 removed
2 unmodified lines34567789101114 unmodified lines2 unmodified lines <img class="logo" src="{{ pathto('_static/requests-sidebar.png', 1) }}" alt="Logo"/> </a></p><p><iframe src="http://markdotto.github.com/github-buttons/github-btn.html?user=kennethreitz&repo=requests&type=watch&count=true&size=large"<iframe src="http://ghbtns.com/github-btn.html?user=kennethreitz&repo=requests&type=watch&count=true&size=large" allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe></p>
<p>14 unmodified linesmodified:docs/_themes/kr/theme.conf+1 added-1 removed
2 unmodified lines3 stylesheet = flasky.css4 pygments_style = flask_theme_support.FlaskyStyle5 6 [options]7-touch_icon = 7+touch_icon =modified:docs/_themes/kr_small/static/flasky.css_t+22 added-22 removed
6 unmodified lines7 * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.8 * :license: BSD, see LICENSE for details.9 *10 */11- 11+12 @import url("basic.css");13- 13+14 /* -- page layout ----------------------------------------------------------- */15- 15+16 body {17 font-family: 'Georgia', serif;18 font-size: 17px;19 color: #000;14 unmodified lines34 35 hr {36 border: 1px solid #B1B4B6;37 }38- 38+39 div.body {40 background-color: #ffffff;41 color: #3E4349;42 padding: 0 30px 30px 30px;2 unmodified lines45 img.floatingflask {46 padding: 0 0 10px 10px;47 float: right;48 }49- 49+50 div.footer {51 text-align: right;52 color: #888;53 padding: 10px;54 font-size: 14px;55 width: 650px;56 margin: 0 auto 40px auto;57 }58- 58+59 div.footer a {60 color: #888;61 text-decoration: underline;62 }63- 63+64 div.related {65 line-height: 32px;66 color: #888;67 }68 69 div.related ul {70 padding: 0 0 0 10px;71 }72- 72+73 div.related a {74 color: #444;75 }76- 76+77 /* -- body styles ----------------------------------------------------------- */78- 78+79 a {80 color: #004B6B;81 text-decoration: underline;82 }83- 83+84 a:hover {85 color: #6D4100;86 text-decoration: underline;87 }88 89 div.body {90 padding-bottom: 40px; /* saved for footer */91 }92- 92+93 div.body h1,94 div.body h2,95 div.body h3,96 div.body h4,11 unmodified lines108 background: url({{ theme_index_logo }}) no-repeat center center;109 height: {{ theme_index_logo_height }};110 }111 {% endif %}112- 112+113 div.body h2 { font-size: 180%; }114 div.body h3 { font-size: 150%; }115 div.body h4 { font-size: 130%; }116 div.body h5 { font-size: 100%; }117 div.body h6 { font-size: 100%; }118- 118+119 a.headerlink {120 color: white;121 padding: 0 4px;122 text-decoration: none;123 }124- 124+125 a.headerlink:hover {126 color: #444;127 background: #eaeaea;128 }129- 129+130 div.body p, div.body dd, div.body li {131 line-height: 1.4em;132 }133 29 unmodified lines163 div.note {164 background-color: #eee;165 border: 1px solid #ccc;166 }167- 167+168 div.seealso {169 background-color: #ffc;170 border: 1px solid #ff6;171 }172- 172+173 div.topic {174 background-color: #eee;175 }176- 176+177 div.warning {178 background-color: #ffe4e4;179 border: 1px solid #f66;180 }181- 181+182 p.admonition-title {183 display: inline;184 }185- 185+186 p.admonition-title:after {187 content: ":";188 }189 63 unmodified lines253 254 dl dd {255 margin-left: 30px;256 }257- 257+258 pre {259 padding: 0;260 margin: 15px -30px;261 padding: 8px;26 unmodified linesmodified:docs/_themes/LICENSE+2 added-2 removed
1-Modifications: 1+Modifications:2 3 Copyright (c) 2011 Kenneth Reitz.4 5 6-Original Project: 6+Original Project:7 8 Copyright (c) 2010 by Armin Ronacher.9 10 35 unmodified linesmodified:docs/_themes/README.rst+1 added-1 removed
1 krTheme Sphinx Style2 ====================3 4-This repository contains sphinx styles Kenneth Reitz uses in most of 4+This repository contains sphinx styles Kenneth Reitz uses in most of5 his projects. It is a derivative of Mitsuhiko's themes for Flask and Flask related6 projects. To use this style in your Sphinx documentation, follow7 this guide:8 17 unmodified linesmodified:docs/user/advanced.rst+25 added
341 unmodified lines342 proxies = {343 "http": "http://user:pass@10.10.1.10:3128/",344 }345 346+Compliance347+----------348 349+Requests is intended to be compliant with all relevant specifications and350+RFCs where that compliance will not cause difficulties for users. This351+attention to the specification can lead to some behaviour that may seem352+unusual to those not familiar with the relevant specification.353+354+Encodings355+^^^^^^^^^356+357+When you receive a response, Requests makes a guess at the encoding to use for358+decoding the response when you call the ``Response.text`` method. Requests359+will first check for an encoding in the HTTP header, and if none is present,360+will use `chardet <http://pypi.python.org/pypi/chardet>`_ to attempt to guess361+the encoding.362+363+The only time Requests will not do this is if no explicit charset is present364+in the HTTP headers **and** the ``Content-Type`` header contains ``text``. In365+this situation,366+`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_367+specifies that the default charset must be ``ISO-8859-1``. Requests follows368+the specification in this case. If you require a different encoding, you can369+manually set the ``Response.encoding`` property, or use the raw370+``Request.content``.371+372 HTTP Verbs373 ----------374 375 Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,151 unmodified linesmodified:docs/user/quickstart.rst+24 added-14 removed
22 unmodified lines23 24 Making a request with Requests is very simple.25 26 Begin by importing the Requests module::27- 27+28 >>> import requests29 30 Now, let's try to get a webpage. For this example, let's get GitHub's public31 timeline ::4 unmodified lines36 information we need from this object.37 38 Requests' simple API means that all forms of HTTP request are as obvious. For39 example, this is how you make an HTTP POST request::40- 40+41 >>> r = requests.post("http://httpbin.org/post")42 43 Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and44 OPTIONS? These are all just as simple::45- 45+46 >>> r = requests.put("http://httpbin.org/put")47 >>> r = requests.delete("http://httpbin.org/delete")48 >>> r = requests.head("http://httpbin.org/get")49 >>> r = requests.options("http://httpbin.org/get")19 unmodified lines69 You can see that the URL has been correctly encoded by printing the URL::70 71 >>> print r.url72 u'http://httpbin.org/get?key2=value2&key1=value1'73- 73 74+75 Response Content76 ----------------77 78 We can read the content of the server's response. Consider the GitHub timeline6 unmodified lines85 86 Requests will automatically decode content from the server. Most unicode87 charsets are seamlessly decoded.88 89-When you make a request, ``r.encoding`` is set, based on the HTTP headers.90-Requests will use that encoding when you access ``r.text``. If ``r.encoding``91-is ``None``, Requests will make an extremely educated guess of the encoding92-of the response body. You can manually set ``r.encoding`` to any encoding93-you'd like, and that charset will be used.89+When you make a request, Requests makes educated guesses about the encoding of90+the response based on the HTTP headers. The text encoding guessed by Requests91+is used when you access ``r.text``. You can find out what encoding Requests is92+using, and change it, using the ``r.encoding`` property::93 94+ >>> r.encoding95+ 'utf-8'96+ >>> r.encoding = 'ISO-8859-1'97 98+If you change the encoding, Requests will use the new value of ``r.encoding``99+whenever you call ``r.text``.100+101+Requests will also use custom encodings in the event that you need them. If102+you have created your own encoding and registered it with the ``codecs``103+module, you can simply use the codec name as the value of ``r.encoding`` and104+Requests will handle the decoding for you.105+106 Binary Response Content107 -----------------------108 109 You can also access the response body as bytes, for non-text requests::118 unmodified lines228 229 If you want, you can send strings to be received as files::230 231 >>> url = 'http://httpbin.org/post'222- >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')} 232+ >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}233 234 >>> r = requests.post(url, files=files)235 >>> r.text236 {22 unmodified lines259 260 If we made a bad request (non-200 response), we can raise it with261 :class:`Response.raise_for_status()`::262 253- >>> _r = requests.get('http://httpbin.org/status/404')254- >>> _r.status_code263+ >>> bad_r = requests.get('http://httpbin.org/status/404')264+ >>> bad_r.status_code265 404266 257- >>> _r.raise_for_status()267+ >>> bad_r.raise_for_status()268 Traceback (most recent call last):269 File "requests/models.py", line 832, in raise_for_status270 raise http_error271 requests.exceptions.HTTPError: 404 Client Error66 unmodified lines338 339 Basic Authentication340 --------------------341 332-Many web services require authentication. There many different types of342+Many web services require authentication. There are many different types of343 authentication, but the most common is HTTP Basic Auth.344 345 Making requests with Basic Auth is extremely simple::346 116 unmodified linesmodified:docs/MANIFEST.in+1 added-1 removed
1-include HISTORY.rst README.rst LICENSE 1+include HISTORY.rst README.rst LICENSEmodified:requests/api.py+2 added
12 unmodified lines13 14 from . import sessions15 from .safe_mode import catch_exceptions_if_in_safe_mode16 17+18 @catch_exceptions_if_in_safe_mode19 def request(method, url, **kwargs):20 """Constructs and sends a :class:`Request <Request>`.21 Returns :class:`Response <Response>` object.30 unmodified lines52 finally:53 if adhoc_session:54 session.close()55 56+57 def get(url, **kwargs):58 """Sends a GET request. Returns :class:`Response` object.59 60 :param url: URL for the new :class:`Request` object.70 unmodified linesmodified:requests/auth.py+3 added
32 unmodified lines33 log = logging.getLogger(__name__)34 35 CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'36 37+38 def _basic_auth_str(username, password):39 """Returns a Basic Auth string."""40 41 return 'Basic ' + b64encode(('%s:%s' % (username, password)).encode('latin1')).strip().decode('latin1')197 unmodified lines239 def __call__(self, r):240 r.register_hook('response', self.handle_401)241 return r242 243+244 def _negotiate_value(r):245 """Extracts the gssapi authentication token from the appropriate header"""246 247 authreq = r.headers.get('www-authenticate', None)5 unmodified lines253 return mo.group(1)254 255 return None256 257+258 class HTTPKerberosAuth(AuthBase):259 """Attaches HTTP GSSAPI/Kerberos Authentication to the given Request object."""260 def __init__(self, require_mutual_auth=True):261 if k is None:103 unmodified linesmodified:requests/compat.py-1 removed
110 unmodified lines111 str = str112 bytes = bytes113 basestring = (str,bytes)114 numeric_types = (int, float)115-modified:requests/cookies.py+20 added-10 removed
12 unmodified lines13 threading14 except ImportError:15 import dummy_threading as threading16 17+18 class MockRequest(object):19 """Wraps a `requests.Request` to mimic a `urllib2.Request`.20 21 The code in `cookielib.CookieJar` expects this interface in order to correctly44 unmodified lines66 67 def get_new_headers(self):68 return self._new_headers69 70+71 class MockResponse(object):72 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.73 74 ...what? Basically, expose the parsed HTTP headers from the server response12 unmodified lines87 88 def getheaders(self, name):89 self._headers.getheaders(name)90 91+92 def extract_cookies_to_jar(jar, request, response):93 """Extract the cookies from the response into a CookieJar.94 95 :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)5 unmodified lines101 # 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)104 105+106 def get_cookie_header(jar, request):107 """Produce an appropriate Cookie header string to be sent with `request`, or None."""108 r = MockRequest(request)109 jar.add_cookie_header(r)110 return r.get_new_headers().get('Cookie')111 112+113 def remove_cookie_by_name(cookiejar, name, domain=None, path=None):114 """Unsets a cookie by name, by default over all domains and paths.115 116 Wraps CookieJar.clear(), is O(n).7 unmodified lines124 125 for domain, path, name in clearables:126 cookiejar.clear(domain, path, name)127 128+129 class CookieConflictError(RuntimeError):124- """There are two cookies that meet the criteria specified in the cookie jar. 130+ """There are two cookies that meet the criteria specified in the cookie jar.131 Use .get and .set and include domain and path args in order to be more specific."""132 133+134 class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):135 """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface.136 137 This is the CookieJar we create by default for requests and sessions that49 unmodified lines187 values = []188 for cookie in iter(self):189 values.append(cookie.value)190 return values184- 191+192 def items(self):193 """Dict-like items() that returns a list of name-value tuples from the jar.194 See keys() and values(). Allows client-code to call "dict(RequestsCookieJar)195 and get a vanilla python dict of key value pairs."""25 unmodified lines221 for cookie in iter(self):222 if cookie.domain is not None and cookie.domain in domains:223 return True224 domains.append(cookie.domain)218- return False # there is only one domain in jar225+ return False # there is only one domain in jar226 227 def get_dict(self, domain=None, path=None):228 """Takes as an argument an optional domain and path and returns a plain old229 Python dict of name-value pairs of cookies that meet the requirements."""230 dictionary = {}231 for cookie in iter(self):225- if (domain == None or cookie.domain == domain) and (path == None 232+ if (domain == None or cookie.domain == domain) and (path == None233 or cookie.path == path):234 dictionary[cookie.name] = cookie.value235 return dictionary236 13 unmodified lines250 """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""251 remove_cookie_by_name(self, name)252 253 def _find(self, name, domain=None, path=None):247- """Requests uses this method internally to get cookie values. Takes as args name 254+ """Requests uses this method internally to get cookie values. Takes as args name255 and optional domain and path. Returns a cookie.value. If there are conflicting cookies,256 _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown257 if there are conflicting cookies."""258 for cookie in iter(self):4 unmodified lines263 264 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))265 266 def _find_no_duplicates(self, name, domain=None, path=None):260- """__get_item__ and get call _find_no_duplicates -- never used in Requests internally. 261- Takes as args name and optional domain and path. Returns a cookie.value. 262- Throws KeyError if cookie is not found and CookieConflictError if there are 267+ """__get_item__ and get call _find_no_duplicates -- never used in Requests internally.268+ Takes as args name and optional domain and path. Returns a cookie.value.269+ Throws KeyError if cookie is not found and CookieConflictError if there are270 multiple cookies that match name and optionally domain and path."""271 toReturn = None272 for cookie in iter(self):273 if cookie.name == name:274 if domain is None or cookie.domain == domain:275 if path is None or cookie.path == path:269- if toReturn != None: # if there are multiple cookies that meet passed in criteria276+ if toReturn != None: # if there are multiple cookies that meet passed in criteria277 raise CookieConflictError('There are multiple cookies with name, %r' % (name))271- toReturn = cookie.value # we will eventually return this as long as no cookie conflict278+ toReturn = cookie.value # we will eventually return this as long as no cookie conflict279 280 if toReturn:281 return toReturn282 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))14 unmodified lines297 def copy(self):298 """This is not implemented. Calling this will throw an exception."""299 raise NotImplementedError300 301+302 def create_cookie(name, value, **kwargs):303 """Make a cookie from underspecified parameters.304 305 By default, the pair of `name` and `value` will be set for the domain ''27 unmodified lines333 result['path_specified'] = bool(result['path'])334 335 return cookielib.Cookie(**result)336 337+338 def morsel_to_cookie(morsel):339 """Convert a Morsel object into a Cookie containing the one k/v pair."""340 c = create_cookie(341 name=morsel.key,15 unmodified lines357 rfc2109=False,358 )359 return c360 361+362 def cookiejar_from_dict(cookie_dict, cookiejar=None):363 """Returns a CookieJar from a key/value dictionary.364 365 :param cookie_dict: Dict of key/values to insert into CookieJar.8 unmodified linesmodified:requests/exceptions.py+10 added
6 unmodified lines7 This module contains the set of Requests' exceptions.8 9 """10 11+12 class RequestException(RuntimeError):13 """There was an ambiguous exception that occurred while handling your14 request."""15 16+17 class HTTPError(RequestException):18 """An HTTP error occurred."""19 response = None20 21+22 class ConnectionError(RequestException):23 """A Connection error occurred."""24 25+26 class SSLError(ConnectionError):27 """An SSL error occurred."""28 29+30 class Timeout(RequestException):31 """The request timed out."""32 33+34 class URLRequired(RequestException):35 """A valid URL is required to make a request."""36 37+38 class TooManyRedirects(RequestException):39 """Too many redirects."""40 41+42 class MissingSchema(RequestException, ValueError):43 """The URL schema (e.g. http or https) is missing."""44 45+46 class InvalidSchema(RequestException, ValueError):47 """See defaults.py for valid schemas."""48 49+50 class InvalidURL(RequestException, ValueError):51 """ The URL provided was somehow invalid. """modified:requests/hooks.py+1 added
28 unmodified lines29 30 31 HOOKS = ('args', 'pre_request', 'pre_send', 'post_request', 'response')32 33+34 def dispatch_hook(key, hooks, hook_data):35 """Dispatches a hook dictionary on a given piece of data."""36 37 hooks = hooks or dict()17 unmodified linesmodified:requests/models.py+42 added-16 removed
6 unmodified lines7 This module contains the primary objects that power Requests.8 """9 10 import os11+import socket12 from datetime import datetime13+from io import BytesIO14 15 from .hooks import dispatch_hook, HOOKS16 from .structures import CaseInsensitiveDict17 from .status_codes import codes55 unmodified lines73 # (Use socket.setdefaulttimeout() as fallback)74 self.timeout = timeout75 76 #: Request URL.77+ #: Accept objects that have string representations.78+ try:79+ self.url = unicode(url)80+ except NameError:81+ # We're on Python 3.82+ self.url = str(url)83+ except UnicodeDecodeError:75- self.url = url84+ self.url = url85 86 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.87 self.headers = dict(headers or [])88 211 unmodified lines300 _poolmanager=self._poolmanager,301 proxies=self.proxies,302 verify=self.verify,303 session=self.session,295- cert=self.cert304+ cert=self.cert,305+ prefetch=self.prefetch,306 )307 308 request.send()309 r = request.response27 unmodified lines337 else:338 return data339 340 def _encode_files(self, files):341+ """Build the body for a multipart/form-data request.342 343+ Will successfully encode files when passed as a dict or a list of344+ 2-tuples. Order is retained if data is a list of 2-tuples but abritrary345+ if parameters are supplied as a dict.346+347+ """348 if (not files) or isinstance(self.data, str):349 return None350 351 fields = to_key_val_list(self.data)5 unmodified lines357 fn, fp = v358 else:359 fn = guess_filename(v) or k360 fp = v345- if isinstance(fp, (bytes, str)):361+ if isinstance(fp, str):362 fp = StringIO(fp)363+ if isinstance(fp, bytes):364+ fp = BytesIO(fp)365 fields.append((k, (fn, fp.read())))366 367 new_fields = []368 for field, val in fields:351- if isinstance(val, float):352- new_fields.append((field, str(val)))353- elif isinstance(val, list):354- newvalue = ', '.join(val)355- new_fields.append((field, newvalue))369+ if isinstance(val, list):370+ for v in val:371+ new_fields.append((k, str(v)))372 else:357- new_fields.append((field, val))358- fields = new_fields359- (body, content_type) = encode_multipart_formdata(fields)373+ new_fields.append((field, str(val)))374+ body, content_type = encode_multipart_formdata(new_fields)375 361- return (body, content_type)376+ return body, content_type377 378 @property379 def full_url(self):380 """Build the actual URL to use."""11 unmodified lines392 393 if not scheme in SCHEMAS:394 raise InvalidSchema("Invalid scheme %r" % scheme)395 396+ try:381- netloc = netloc.encode('idna').decode('utf-8')397+ netloc = netloc.encode('idna').decode('utf-8')398+ except UnicodeError:399+ raise InvalidURL('URL has an invalid label.')400 401 if not path:402 path = '/'403 65 unmodified lines469 return True470 except ValueError:471 return False472 455- def send(self, anyway=False, prefetch=True):473+ def send(self, anyway=False, prefetch=None):474 """Sends the request. Returns True if successful, False if not.475 If there was an HTTPError during transmission,476 self.response.status_code will contain the HTTPError code.477 478 Once a request is successfully sent, `sent` will equal True.479 480 :param anyway: If True, request will be sent, even if it has481 already been sent.482+483+ :param prefetch: If not None, will override the request's own setting484+ for prefetch.485 """486 487 # Build the URL488 url = self.full_url43 unmodified lines532 # Update self to reflect the auth changes.533 self.__dict__.update(r.__dict__)534 535 _p = urlparse(url)515- no_proxy = filter(lambda x:x.strip(), self.proxies.get('no', '').split(','))536+ no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))537 proxy = self.proxies.get(_p.scheme)538 539 if proxy and not any(map(_p.netloc.endswith, no_proxy)):540 conn = poolmanager.proxy_from_url(proxy)77 unmodified lines618 timeout=self.timeout,619 )620 self.sent = True621 622+ except socket.error as sockerr:623+ raise ConnectionError(sockerr)624+625 except MaxRetryError as e:626 raise ConnectionError(e)627 628 except (_SSLError, _HTTPError) as e:14 unmodified lines643 r = dispatch_hook('post_request', self.hooks, self)644 self.__dict__.update(r.__dict__)645 646 # If prefetch is True, mark content as consumed.623- if prefetch or self.prefetch:647+ if prefetch is None:648+ prefetch = self.prefetch649+ if prefetch:650 # Save the response.651 self.response.content652 653 if self.config.get('danger_mode'):212 unmodified linesmodified:requests/safe_mode.py+5 added-4 removed
14 unmodified lines15 from .packages.urllib3.response import HTTPResponse16 from .exceptions import RequestException, ConnectionError, HTTPError17 import socket18 19+20 def catch_exceptions_if_in_safe_mode(function):21 """New implementation of safe_mode. We catch all exceptions at the API level22 and then return a blank Response object with the error field filled. This decorator23 wraps request() in api.py.24 """24- 25+26 def wrapped(method, url, **kwargs):27 # if save_mode, we catch exceptions and fill error field27- if (kwargs.get('config') and kwargs.get('config').get('safe_mode')) or (kwargs.get('session') 28+ if (kwargs.get('config') and kwargs.get('config').get('safe_mode')) or (kwargs.get('session')29 and kwargs.get('session').config.get('safe_mode')):30 try:31 return function(method, url, **kwargs)32 except (RequestException, ConnectionError, HTTPError,33 socket.timeout, socket.gaierror) as e:34 r = Response()35 r.error = e35- r.raw = HTTPResponse() # otherwise, tests fail36- r.status_code = 0 # with this status_code, content returns None36+ r.raw = HTTPResponse() # otherwise, tests fail37+ r.status_code = 0 # with this status_code, content returns None38 return r39 return function(method, url, **kwargs)40 return wrappedmodified:requests/sessions.py-7 removed
242 unmodified lines243 244 # Return the response.245 return r.response246 247-247 def get(self, url, **kwargs):248 """Sends a GET request. Returns :class:`Response` object.249 250 :param url: URL for the new :class:`Request` object.2 unmodified lines253 254 kwargs.setdefault('allow_redirects', True)255 return self.request('get', url, **kwargs)256 258-257 def options(self, url, **kwargs):258 """Sends a OPTIONS request. Returns :class:`Response` object.259 260 :param url: URL for the new :class:`Request` object.2 unmodified lines263 264 kwargs.setdefault('allow_redirects', True)265 return self.request('options', url, **kwargs)266 269-267 def head(self, url, **kwargs):268 """Sends a HEAD request. Returns :class:`Response` object.269 270 :param url: URL for the new :class:`Request` object.2 unmodified lines273 274 kwargs.setdefault('allow_redirects', False)275 return self.request('head', url, **kwargs)276 280-277 def post(self, url, data=None, **kwargs):278 """Sends a POST request. Returns :class:`Response` object.279 280 :param url: URL for the new :class:`Request` object.2 unmodified lines283 """284 285 return self.request('post', url, data=data, **kwargs)286 291-287 def put(self, url, data=None, **kwargs):288 """Sends a PUT request. Returns :class:`Response` object.289 290 :param url: URL for the new :class:`Request` object.2 unmodified lines293 """294 295 return self.request('put', url, data=data, **kwargs)296 302-297 def patch(self, url, data=None, **kwargs):298 """Sends a PATCH request. Returns :class:`Response` object.299 300 :param url: URL for the new :class:`Request` object.2 unmodified lines303 """304 305 return self.request('patch', url, data=data, **kwargs)306 313-307 def delete(self, url, **kwargs):308 """Sends a DELETE request. Returns :class:`Response` object.309 310 :param url: URL for the new :class:`Request` object.19 unmodified linesmodified:requests/status_codes.py+1 added-1 removed
81 unmodified lines82 for (code, titles) in list(_codes.items()):83 for title in titles:84 setattr(codes, title, code)85 if not title.startswith('\\'):86- setattr(codes, title.upper(), code)86+ setattr(codes, title.upper(), code)modified:requests/structures.py+1 added
45 unmodified lines46 return self[key]47 else:48 return default49 50+51 class LookupDict(dict):52 """Dictionary lookup object."""53 54 def __init__(self, name=None):13 unmodified linesmodified:requests/utils.py+3 added
47 unmodified lines48 # as a fallback (which is generated from pem files in the 'certs' directory):49 '/etc/ssl/ca-bundle.pem',50 ]51 52+53 def get_os_ca_bundle_path():54 """Try to pick an available CA certificate bundle provided by the OS."""55 for path in POSSIBLE_CA_BUNDLE_PATHS:56 if os.path.exists(path):3 unmodified lines60 # if certifi is installed, use its CA bundle;61 # otherwise, try and use the OS bundle62 DEFAULT_CA_BUNDLE_PATH = CERTIFI_BUNDLE_PATH or get_os_ca_bundle_path()63 64+65 def dict_to_sequence(d):66 """Returns an internal sequence dictionary update."""67 68 if hasattr(d, 'items'):404 unmodified lines473 # Then quote only illegal characters (do not quote reserved, unreserved,474 # or '%')475 return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")476 477+478 def get_environ_proxies():479 """Return a dict of environment proxies."""480 481 proxy_keys = [39 unmodified linesmodified:tests/informal/test_leaked_connections.py+1 added
4 unmodified lines5 """6 7 import gc, os, subprocess, requests, sys8 9+10 def main():11 gc.disable()12 13 for x in range(20):14 unmodified linesmodified:tests/test_cookies.py+12 added-9 removed
14 unmodified lines15 # More hacks16 sys.path.append('.')17 from test_requests import httpbin, TestBaseMixin18 19+20 class CookieTests(TestBaseMixin, unittest.TestCase):21 22 def test_cookies_from_response(self):23 """Basic test that we correctly parse received cookies in the Response object."""82 unmodified lines106 107 def test_disabled_cookie_persistence(self):108 """Test that cookies are not persisted when configured accordingly."""109 109- config = {'store_cookies' : False}110+ config = {'store_cookies': False}111 112 # Check the case when no cookie is passed as part of the request and the one in response is ignored112- cookies = requests.get(httpbin('cookies', 'set', 'key', 'value'), config = config).cookies113+ cookies = requests.get(httpbin('cookies', 'set', 'key', 'value'), config=config).cookies114 self.assertTrue(cookies.get("key") is None)115 116 # Test that the cookies passed while making the request still gets used and is available in response object.117 # only the ones received from server is not saved117- cookies_2 = requests.get(httpbin('cookies', 'set', 'key', 'value'), config = config,\118- cookies = {"key_2" : "value_2"}).cookies118+ cookies_2 = requests.get(httpbin('cookies', 'set', 'key', 'value'), config=config,\119+ cookies={"key_2": "value_2"}).cookies120 self.assertEqual(len(cookies_2), 1)121 self.assertEqual(cookies_2.get("key_2"), "value_2")122 123 # Use the session and make sure that the received cookie is not used in subsequent calls124 s = requests.session()124- s.get(httpbin('cookies', 'set', 'key', 'value'), config = config)125+ s.get(httpbin('cookies', 'set', 'key', 'value'), config=config)126 r = s.get(httpbin('cookies'))127 self.assertEqual(json.loads(r.text)['cookies'], {})128 129 def test_jar_utility_functions(self):4 unmodified lines134 self.assertTrue(len(c) >= 1)135 self.assertEqual(len(c), len(r.cookies.keys()))136 self.assertEqual(len(c), len(r.cookies.values()))137 self.assertEqual(len(c), len(r.cookies.items()))137- 138+139 # domain and path utility functions140 domain = r.cookies.list_domains()[0]141 path = r.cookies.list_paths()[0]142 self.assertEqual(dict(r.cookies), r.cookies.get_dict(domain=domain, path=path))8 unmodified lines151 152 # test keys, values, and items153 self.assertEqual(r.cookies.keys(), ['myname'])154 self.assertEqual(r.cookies.values(), ['myvalue'])154- self.assertEqual(r.cookies.items(), [('myname','myvalue')])155- 155+ self.assertEqual(r.cookies.items(), [('myname', 'myvalue')])156+157 # test if we can convert jar to dict158 dictOfCookies = dict(r.cookies)158- self.assertEqual(dictOfCookies, {'myname':'myvalue'})159+ self.assertEqual(dictOfCookies, {'myname': 'myvalue'})160 self.assertEqual(dictOfCookies, r.cookies.get_dict())161 162+163 class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):164 """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""165 166 COOKIEJAR_CLASS = cookielib.LWPCookieJar88 unmodified lines255 # we should only load the persistent cookie256 self.assertEqual(len(cookiejar_2), 1)257 self.assertCookieHas(list(cookiejar_2)[0], name='Persistent', value='CookiesAreScary')258 259+260 class MozCookieJarTest(LWPCookieJarTest):261 """Same test, but substitute MozillaCookieJar."""262 263 COOKIEJAR_CLASS = cookielib.MozillaCookieJar3 unmodified linesmodified:tests/test_requests_ext.py+3 added-11 removed
23 unmodified lines24 25 def test_addition(self):26 assert (1 + 1) == 227 28-28 def test_ssl_hostname_ok(self):29 requests.get('https://github.com', verify=True)30 32-31 def test_ssl_hostname_not_ok(self):32 requests.get('https://kennethreitz.com', verify=False)33 34 self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')35 38-36 def test_ssl_hostname_session_not_ok(self):37 38 s = requests.session()39 40 self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')41 42 s.get('https://kennethreitz.com', verify=False)43 47-44 def test_binary_post(self):45 '''We need to be careful how we build the utf-8 string since46 unicode literals are a syntax error in python347 '''6 unmodified lines54 else:55 raise EnvironmentError('Flesh out this test for your environment.')56 requests.post('http://www.google.com/', data=utf8_string)57 62-63-58 def test_unicode_error(self):59 url = 'http://blip.fm/~1abvfu'60 requests.get(url)61 68-62 def test_chunked_head_redirect(self):63 url = "http://t.co/NFrx0zLG"64 r = requests.head(url, allow_redirects=True)65 self.assertEqual(r.status_code, 200)36 unmodified lines102 # get a cookie for tinyurl.com ONLY103 s = requests.session()104 s.get(url='http://tinyurl.com/preview.php?disable=1')105 # we should have set a cookie for tinyurl: preview=0113- self.assertIn('preview', s.cookies)106+ self.assertTrue('preview' in s.cookies)107 self.assertEqual(s.cookies['preview'], '0')108 self.assertEqual(list(s.cookies)[0].name, 'preview')109 self.assertEqual(list(s.cookies)[0].domain, 'tinyurl.com')110 111 # get cookies on another domain112 r2 = s.get(url='http://httpbin.org/cookies')113 # the cookie is not there121- self.assertNotIn('preview', json.loads(r2.text)['cookies'])114+ self.assertTrue('preview' not in json.loads(r2.text)['cookies'])115 116 # this redirects to another domain, httpbin.org117 # cookies of the first domain should NOT be sent to the next one118 r3 = s.get(url='http://tinyurl.com/7zp3jnr')119 assert r3.url == 'http://httpbin.org/cookies'127- self.assertNotIn('preview', json.loads(r2.text)['cookies'])120+ self.assertTrue('preview' not in json.loads(r2.text)['cookies'])121 122 if __name__ == '__main__':123 unittest.main()131-modified:tests/test_requests_https.py+1 added
7 unmodified lines8 # Path hack.9 sys.path.insert(0, os.path.abspath('..'))10 import requests11 12+13 class HTTPSTest(unittest.TestCase):14 """Smoke test for https functionality."""15 16 smoke_url = "https://github.com"16 unmodified linesmodified:tests/test_requests.py+90 added-3 removed
5 unmodified lines6 # Path hack.7 import sys8 import os9 sys.path.insert(0, os.path.abspath('..'))10-10 import json11 import os12 import unittest13 import pickle4 unmodified lines18 # import envoy19 from requests import HTTPError20 from requests import get, post, head, put21 from requests.auth import HTTPBasicAuth, HTTPDigestAuth22+from requests.exceptions import InvalidURL23 24 if 'HTTPBIN_URL' not in os.environ:25 os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'26 828 unmodified lines855 ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=False)))856 assert ds1.prefetch857 assert not ds2.prefetch858 859+ def test_connection_error(self):860+ try:861+ get('http://localhost:1/nope')862+ except requests.ConnectionError:863+ pass864+ else:865+ assert False866+867+ def test_connection_error_with_safe_mode(self):868+ config = {'safe_mode': True}869+ r = get('http://localhost:1/nope', allow_redirects=False, config=config)870+ assert r.content == None871+872 # def test_invalid_content(self):873 # # WARNING: if you're using a terrible DNS provider (comcast),874 # # this will fail.875 # try:155 unmodified lines1031 """Test that it is possible to POST using the files argument and a1032 list for a value in the data argument."""1033 1034 data = {'field': ['a', 'b']}1022- files = {'file': 'Garbled data'}1035+ files = {'field': 'Garbled data'}1036 r = post(httpbin('post'), data=data, files=files)1037 t = json.loads(r.text)1025- self.assertEqual(t.get('form'), {'field': 'a, b'})1038+ self.assertEqual(t.get('form'), {'field': ['a', 'b']})1039 self.assertEqual(t.get('files'), files)1040 r = post(httpbin('post'), data=data, files=files.items())1041 t = r.json1042 self.assertEqual(t.get('form'), {'field': 'a, b'})4 unmodified lines1047 r = post(httpbin('post'), data=data)1048 t = json.loads(r.text)1049 self.assertEqual(t.get('headers').get('Content-Type'), '')1050 1051+ def test_prefetch_redirect_bug(self):1052+ """Test that prefetch persists across redirections."""1053+ res = get(httpbin('redirect/2'), prefetch=False)1054+ # prefetch should persist across the redirect; if it doesn't,1055+ # this attempt to iterate will crash because the content has already1056+ # been read.1057+ first_line = next(res.iter_lines())1058+ self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))1059 1060+ def test_prefetch_return_response_interaction(self):1061+ """Test that prefetch can be overridden as a kwarg to `send`."""1062+ req = requests.get(httpbin('get'), return_response=False)1063+ req.send(prefetch=False)1064+ # content should not have been prefetched, and iter_lines should succeed1065+ first_line = next(req.response.iter_lines())1066+ self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))1067+1068+ def test_accept_objects_with_string_representations_as_urls(self):1069+ """Test that URLs can be set to objects with string representations,1070+ e.g. for use with furl."""1071+ class URL():1072+ def __unicode__(self):1073+ # Can't have unicode literals in Python3, so avoid them.1074+ # TODO: fixup when moving to Python 3.31075+ if (sys.version_info[0] == 2):1076+ return 'http://httpbin.org/get'.decode('utf-8')1077+ else:1078+ return 'http://httpbin.org/get'1079+1080+ def __str__(self):1081+ return 'http://httpbin.org/get'1082+1083+ r = get(URL())1084+ self.assertEqual(r.status_code, 200)1085+1086+ def test_post_fields_with_multiple_values_and_files_as_tuples(self):1087+ """Test that it is possible to POST multiple data and file fields1088+ with the same name.1089+ https://github.com/kennethreitz/requests/pull/7461090+ """1091+1092+ fields = [1093+ ('__field__', '__value__'),1094+ ('__field__', '__value__'),1095+ ]1096+1097+ r = post(httpbin('post'), data=fields, files=fields)1098+ t = json.loads(r.text)1099+1100+ self.assertEqual(t.get('form'), {1101+ '__field__': [1102+ '__value__',1103+ '__value__',1104+ ]1105+ })1106+1107+ # It's not currently possible to test for multiple file fields with1108+ # the same name against httpbin so we need to inspect the encoded1109+ # body manually.1110+ request = r.request1111+ body, content_type = request._encode_files(request.files)1112+ file_field = (b'Content-Disposition: form-data;'1113+ b' name="__field__"; filename="__field__"')1114+ self.assertEqual(body.count(b'__value__'), 4)1115+ self.assertEqual(body.count(file_field), 2)1116+1117+ def test_bytes_files(self):1118+ """Test that `bytes` can be used as the values of `files`."""1119+ post(httpbin('post'), files={'test': b'test'})1120+1121+ def test_invalid_urls_throw_requests_exception(self):1122+ """Test that URLs with invalid labels throw1123+ Requests.exceptions.InvalidURL instead of UnicodeError."""1124+ self.assertRaises(InvalidURL, get, 'http://.google.com/')1125+1126 if __name__ == '__main__':1127 unittest.main()modified:AUTHORS.rst+1 added
108 unmodified lines109 - Sarah Gonzalez110 - Victoria Mo111 - Leila Muhtasib112 - Matthias Rahlf <matthias@webding.de>113+- Jakub Roztocil <jakub@roztocil.name>