Skip to content
Myr

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

27 files+274 added−105 removed

modified:docs/_templates/sidebarintro.html+1 added-1 removed
modified:docs/_templates/sidebarlogo.html+1 added-1 removed
modified:docs/_themes/kr/theme.conf+1 added-1 removed
2 unmodified lines
3stylesheet = flasky.css4pygments_style = flask_theme_support.FlaskyStyle56[options]7touch_icon = 7touch_icon =
modified:docs/_themes/kr_small/static/flasky.css_t+22 added-22 removed
6 unmodified lines
7 * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.8 * :license: BSD, see LICENSE for details.9 *10 */11 1112@import url("basic.css");13 1314/* -- page layout ----------------------------------------------------------- */15 1516body {17 font-family: 'Georgia', serif;18 font-size: 17px;19 color: #000;
14 unmodified lines
3435hr {36 border: 1px solid #B1B4B6;37}38 3839div.body {40 background-color: #ffffff;41 color: #3E4349;42 padding: 0 30px 30px 30px;
2 unmodified lines
45img.floatingflask {46 padding: 0 0 10px 10px;47 float: right;48}49 4950div.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 5859div.footer a {60 color: #888;61 text-decoration: underline;62}63 6364div.related {65 line-height: 32px;66 color: #888;67}6869div.related ul {70 padding: 0 0 0 10px;71}72 7273div.related a {74 color: #444;75}76 7677/* -- body styles ----------------------------------------------------------- */78 7879a {80 color: #004B6B;81 text-decoration: underline;82}83 8384a:hover {85 color: #6D4100;86 text-decoration: underline;87}8889div.body {90 padding-bottom: 40px; /* saved for footer */91}92 9293div.body h1,94div.body h2,95div.body h3,96div.body h4,
11 unmodified lines
108 background: url({{ theme_index_logo }}) no-repeat center center;109 height: {{ theme_index_logo_height }};110}111{% endif %}112 112113div.body h2 { font-size: 180%; }114div.body h3 { font-size: 150%; }115div.body h4 { font-size: 130%; }116div.body h5 { font-size: 100%; }117div.body h6 { font-size: 100%; }118 118119a.headerlink {120 color: white;121 padding: 0 4px;122 text-decoration: none;123}124 124125a.headerlink:hover {126 color: #444;127 background: #eaeaea;128}129 129130div.body p, div.body dd, div.body li {131 line-height: 1.4em;132}133
29 unmodified lines
163div.note {164 background-color: #eee;165 border: 1px solid #ccc;166}167 167168div.seealso {169 background-color: #ffc;170 border: 1px solid #ff6;171}172 172173div.topic {174 background-color: #eee;175}176 176177div.warning {178 background-color: #ffe4e4;179 border: 1px solid #f66;180}181 181182p.admonition-title {183 display: inline;184}185 185186p.admonition-title:after {187 content: ":";188}189
63 unmodified lines
253254dl dd {255 margin-left: 30px;256}257 257258pre {259 padding: 0;260 margin: 15px -30px;261 padding: 8px;
26 unmodified lines
modified:docs/_themes/LICENSE+2 added-2 removed
1Modifications: 1Modifications:23Copyright (c) 2011 Kenneth Reitz.456Original Project: 6Original Project:78Copyright (c) 2010 by Armin Ronacher.910
35 unmodified lines
modified:docs/_themes/README.rst+1 added-1 removed
1krTheme Sphinx Style2====================34This repository contains sphinx styles Kenneth Reitz uses in most of 4This repository contains sphinx styles Kenneth Reitz uses in most of5his projects. It is a derivative of Mitsuhiko's themes for Flask and Flask related6projects. To use this style in your Sphinx documentation, follow7this guide:8
17 unmodified lines
modified:docs/user/advanced.rst+25 added
341 unmodified lines
342 proxies = {343 "http": "http://user:pass@10.10.1.10:3128/",344 }345346Compliance347----------348349Requests is intended to be compliant with all relevant specifications and350RFCs where that compliance will not cause difficulties for users. This351attention to the specification can lead to some behaviour that may seem352unusual to those not familiar with the relevant specification.353354Encodings355^^^^^^^^^356357When you receive a response, Requests makes a guess at the encoding to use for358decoding the response when you call the ``Response.text`` method. Requests359will first check for an encoding in the HTTP header, and if none is present,360will use `chardet <http://pypi.python.org/pypi/chardet>`_ to attempt to guess361the encoding.362363The only time Requests will not do this is if no explicit charset is present364in the HTTP headers **and** the ``Content-Type`` header contains ``text``. In365this situation,366`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_367specifies that the default charset must be ``ISO-8859-1``. Requests follows368the specification in this case. If you require a different encoding, you can369manually set the ``Response.encoding`` property, or use the raw370``Request.content``.371372HTTP Verbs373----------374375Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,
151 unmodified lines
modified:docs/user/quickstart.rst+24 added-14 removed
22 unmodified lines
2324Making a request with Requests is very simple.2526Begin by importing the Requests module::27 2728 >>> import requests2930Now, let's try to get a webpage. For this example, let's get GitHub's public31timeline ::
4 unmodified lines
36information we need from this object.3738Requests' simple API means that all forms of HTTP request are as obvious. For39example, this is how you make an HTTP POST request::40 4041 >>> r = requests.post("http://httpbin.org/post")4243Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and44OPTIONS? These are all just as simple::45 4546 >>> 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 lines
69You can see that the URL has been correctly encoded by printing the URL::7071 >>> print r.url72 u'http://httpbin.org/get?key2=value2&key1=value1'73 737475Response Content76----------------7778We can read the content of the server's response. Consider the GitHub timeline
6 unmodified lines
8586Requests will automatically decode content from the server. Most unicode87charsets are seamlessly decoded.8889When you make a request, ``r.encoding`` is set, based on the HTTP headers.90Requests will use that encoding when you access ``r.text``. If ``r.encoding``91is ``None``, Requests will make an extremely educated guess of the encoding92of the response body. You can manually set ``r.encoding`` to any encoding93you'd like, and that charset will be used.89When you make a request, Requests makes educated guesses about the encoding of90the response based on the HTTP headers. The text encoding guessed by Requests91is used when you access ``r.text``. You can find out what encoding Requests is92using, and change it, using the ``r.encoding`` property::9394 >>> r.encoding95 'utf-8'96 >>> r.encoding = 'ISO-8859-1'9798If you change the encoding, Requests will use the new value of ``r.encoding``99whenever you call ``r.text``.100101Requests will also use custom encodings in the event that you need them. If102you have created your own encoding and registered it with the ``codecs``103module, you can simply use the codec name as the value of ``r.encoding`` and104Requests will handle the decoding for you.105106Binary Response Content107-----------------------108109You can also access the response body as bytes, for non-text requests::
118 unmodified lines
228229If you want, you can send strings to be received as files::230231 >>> 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')}233234 >>> r = requests.post(url, files=files)235 >>> r.text236 {
22 unmodified lines
259260If we made a bad request (non-200 response), we can raise it with261:class:`Response.raise_for_status()`::262253 >>> _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 404266257 >>> _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 Error
66 unmodified lines
338339Basic Authentication340--------------------341332Many web services require authentication. There many different types of342Many web services require authentication. There are many different types of343authentication, but the most common is HTTP Basic Auth.344345Making requests with Basic Auth is extremely simple::346
116 unmodified lines
modified:docs/MANIFEST.in+1 added-1 removed
1include HISTORY.rst README.rst LICENSE 1include HISTORY.rst README.rst LICENSE
modified:requests/api.py+2 added
12 unmodified lines
1314from . import sessions15from .safe_mode import catch_exceptions_if_in_safe_mode161718@catch_exceptions_if_in_safe_mode19def request(method, url, **kwargs):20 """Constructs and sends a :class:`Request <Request>`.21 Returns :class:`Response <Response>` object.
30 unmodified lines
52 finally:53 if adhoc_session:54 session.close()555657def get(url, **kwargs):58 """Sends a GET request. Returns :class:`Response` object.5960 :param url: URL for the new :class:`Request` object.
70 unmodified lines
modified:requests/auth.py+3 added
32 unmodified lines
33log = logging.getLogger(__name__)3435CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'363738def _basic_auth_str(username, password):39 """Returns a Basic Auth string."""4041 return 'Basic ' + b64encode(('%s:%s' % (username, password)).encode('latin1')).strip().decode('latin1')
197 unmodified lines
239 def __call__(self, r):240 r.register_hook('response', self.handle_401)241 return r242243244def _negotiate_value(r):245 """Extracts the gssapi authentication token from the appropriate header"""246247 authreq = r.headers.get('www-authenticate', None)
5 unmodified lines
253 return mo.group(1)254255 return None256257258class 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 lines
modified:requests/compat.py-1 removed
110 unmodified lines
111 str = str112 bytes = bytes113 basestring = (str,bytes)114 numeric_types = (int, float)115
modified:requests/cookies.py+20 added-10 removed
12 unmodified lines
13 threading14except ImportError:15 import dummy_threading as threading161718class MockRequest(object):19 """Wraps a `requests.Request` to mimic a `urllib2.Request`.2021 The code in `cookielib.CookieJar` expects this interface in order to correctly
44 unmodified lines
6667 def get_new_headers(self):68 return self._new_headers697071class MockResponse(object):72 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.7374 ...what? Basically, expose the parsed HTTP headers from the server response
12 unmodified lines
8788 def getheaders(self, name):89 self._headers.getheaders(name)909192def extract_cookies_to_jar(jar, request, response):93 """Extract the cookies from the response into a CookieJar.9495 :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
5 unmodified lines
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)104105106def 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')111112113def remove_cookie_by_name(cookiejar, name, domain=None, path=None):114 """Unsets a cookie by name, by default over all domains and paths.115116 Wraps CookieJar.clear(), is O(n).
7 unmodified lines
124125 for domain, path, name in clearables:126 cookiejar.clear(domain, path, name)127128129class 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."""132133134class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):135 """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface.136137 This is the CookieJar we create by default for requests and sessions that
49 unmodified lines
187 values = []188 for cookie in iter(self):189 values.append(cookie.value)190 return values184 191192 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 lines
221 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 jar226227 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 lines
250 """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""251 remove_cookie_by_name(self, name)252253 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 lines
263264 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))265266 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 conflict279280 if toReturn:281 return toReturn282 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
14 unmodified lines
297 def copy(self):298 """This is not implemented. Calling this will throw an exception."""299 raise NotImplementedError300301302def create_cookie(name, value, **kwargs):303 """Make a cookie from underspecified parameters.304305 By default, the pair of `name` and `value` will be set for the domain ''
27 unmodified lines
333 result['path_specified'] = bool(result['path'])334335 return cookielib.Cookie(**result)336337338def 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 lines
357 rfc2109=False,358 )359 return c360361362def cookiejar_from_dict(cookie_dict, cookiejar=None):363 """Returns a CookieJar from a key/value dictionary.364365 :param cookie_dict: Dict of key/values to insert into CookieJar.
8 unmodified lines
modified:requests/exceptions.py+10 added
6 unmodified lines
7This module contains the set of Requests' exceptions.89"""101112class RequestException(RuntimeError):13 """There was an ambiguous exception that occurred while handling your14 request."""151617class HTTPError(RequestException):18 """An HTTP error occurred."""19 response = None202122class ConnectionError(RequestException):23 """A Connection error occurred."""242526class SSLError(ConnectionError):27 """An SSL error occurred."""282930class Timeout(RequestException):31 """The request timed out."""323334class URLRequired(RequestException):35 """A valid URL is required to make a request."""363738class TooManyRedirects(RequestException):39 """Too many redirects."""404142class MissingSchema(RequestException, ValueError):43 """The URL schema (e.g. http or https) is missing."""444546class InvalidSchema(RequestException, ValueError):47 """See defaults.py for valid schemas."""484950class InvalidURL(RequestException, ValueError):51 """ The URL provided was somehow invalid. """
modified:requests/hooks.py+1 added
28 unmodified lines
293031HOOKS = ('args', 'pre_request', 'pre_send', 'post_request', 'response')323334def dispatch_hook(key, hooks, hook_data):35 """Dispatches a hook dictionary on a given piece of data."""3637 hooks = hooks or dict()
17 unmodified lines
modified:requests/models.py+42 added-16 removed
6 unmodified lines
7This module contains the primary objects that power Requests.8"""910import os11import socket12from datetime import datetime13from io import BytesIO1415from .hooks import dispatch_hook, HOOKS16from .structures import CaseInsensitiveDict17from .status_codes import codes
55 unmodified lines
73 # (Use socket.setdefaulttimeout() as fallback)74 self.timeout = timeout7576 #: 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 = url8586 #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.87 self.headers = dict(headers or [])88
211 unmodified lines
300 _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 )307308 request.send()309 r = request.response
27 unmodified lines
337 else:338 return data339340 def _encode_files(self, files):341 """Build the body for a multipart/form-data request.342343 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.346347 """348 if (not files) or isinstance(self.data, str):349 return None350351 fields = to_key_val_list(self.data)
5 unmodified lines
357 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())))366367 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)375361 return (body, content_type)376 return body, content_type377378 @property379 def full_url(self):380 """Build the actual URL to use."""
11 unmodified lines
392393 if not scheme in SCHEMAS:394 raise InvalidSchema("Invalid scheme %r" % scheme)395396 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.')400401 if not path:402 path = '/'403
65 unmodified lines
469 return True470 except ValueError:471 return False472455 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.477478 Once a request is successfully sent, `sent` will equal True.479480 :param anyway: If True, request will be sent, even if it has481 already been sent.482483 :param prefetch: If not None, will override the request's own setting484 for prefetch.485 """486487 # Build the URL488 url = self.full_url
43 unmodified lines
532 # Update self to reflect the auth changes.533 self.__dict__.update(r.__dict__)534535 _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)538539 if proxy and not any(map(_p.netloc.endswith, no_proxy)):540 conn = poolmanager.proxy_from_url(proxy)
77 unmodified lines
618 timeout=self.timeout,619 )620 self.sent = True621622 except socket.error as sockerr:623 raise ConnectionError(sockerr)624625 except MaxRetryError as e:626 raise ConnectionError(e)627628 except (_SSLError, _HTTPError) as e:
14 unmodified lines
643 r = dispatch_hook('post_request', self.hooks, self)644 self.__dict__.update(r.__dict__)645646 # 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.content652653 if self.config.get('danger_mode'):
212 unmodified lines
modified:requests/safe_mode.py+5 added-4 removed
14 unmodified lines
15from .packages.urllib3.response import HTTPResponse16from .exceptions import RequestException, ConnectionError, HTTPError17import socket181920def 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 2526 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 wrapped
modified:requests/sessions.py-7 removed
242 unmodified lines
243244 # Return the response.245 return r.response246247247 def get(self, url, **kwargs):248 """Sends a GET request. Returns :class:`Response` object.249250 :param url: URL for the new :class:`Request` object.
2 unmodified lines
253254 kwargs.setdefault('allow_redirects', True)255 return self.request('get', url, **kwargs)256258257 def options(self, url, **kwargs):258 """Sends a OPTIONS request. Returns :class:`Response` object.259260 :param url: URL for the new :class:`Request` object.
2 unmodified lines
263264 kwargs.setdefault('allow_redirects', True)265 return self.request('options', url, **kwargs)266269267 def head(self, url, **kwargs):268 """Sends a HEAD request. Returns :class:`Response` object.269270 :param url: URL for the new :class:`Request` object.
2 unmodified lines
273274 kwargs.setdefault('allow_redirects', False)275 return self.request('head', url, **kwargs)276280277 def post(self, url, data=None, **kwargs):278 """Sends a POST request. Returns :class:`Response` object.279280 :param url: URL for the new :class:`Request` object.
2 unmodified lines
283 """284285 return self.request('post', url, data=data, **kwargs)286291287 def put(self, url, data=None, **kwargs):288 """Sends a PUT request. Returns :class:`Response` object.289290 :param url: URL for the new :class:`Request` object.
2 unmodified lines
293 """294295 return self.request('put', url, data=data, **kwargs)296302297 def patch(self, url, data=None, **kwargs):298 """Sends a PATCH request. Returns :class:`Response` object.299300 :param url: URL for the new :class:`Request` object.
2 unmodified lines
303 """304305 return self.request('patch', url, data=data, **kwargs)306313307 def delete(self, url, **kwargs):308 """Sends a DELETE request. Returns :class:`Response` object.309310 :param url: URL for the new :class:`Request` object.
19 unmodified lines
modified:requests/status_codes.py+1 added-1 removed
81 unmodified lines
82for (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 lines
46 return self[key]47 else:48 return default495051class LookupDict(dict):52 """Dictionary lookup object."""5354 def __init__(self, name=None):
13 unmodified lines
modified:requests/utils.py+3 added
47 unmodified lines
48 # as a fallback (which is generated from pem files in the 'certs' directory):49 '/etc/ssl/ca-bundle.pem',50]515253def 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 lines
60# if certifi is installed, use its CA bundle;61# otherwise, try and use the OS bundle62DEFAULT_CA_BUNDLE_PATH = CERTIFI_BUNDLE_PATH or get_os_ca_bundle_path()636465def dict_to_sequence(d):66 """Returns an internal sequence dictionary update."""6768 if hasattr(d, 'items'):
404 unmodified lines
473 # Then quote only illegal characters (do not quote reserved, unreserved,474 # or '%')475 return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")476477478def get_environ_proxies():479 """Return a dict of environment proxies."""480481 proxy_keys = [
39 unmodified lines
modified:tests/informal/test_leaked_connections.py+1 added
4 unmodified lines
5"""67import gc, os, subprocess, requests, sys8910def main():11 gc.disable()1213 for x in range(20):
14 unmodified lines
modified:tests/test_cookies.py+12 added-9 removed
14 unmodified lines
15# More hacks16sys.path.append('.')17from test_requests import httpbin, TestBaseMixin181920class CookieTests(TestBaseMixin, unittest.TestCase):2122 def test_cookies_from_response(self):23 """Basic test that we correctly parse received cookies in the Response object."""
82 unmodified lines
106107 def test_disabled_cookie_persistence(self):108 """Test that cookies are not persisted when configured accordingly."""109109 config = {'store_cookies' : False}110 config = {'store_cookies': False}111112 # 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)115116 # 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")122123 # 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'], {})128129 def test_jar_utility_functions(self):
4 unmodified lines
134 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 138139 # 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 lines
151152 # 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')])156157 # 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())161162163class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):164 """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""165166 COOKIEJAR_CLASS = cookielib.LWPCookieJar
88 unmodified lines
255 # we should only load the persistent cookie256 self.assertEqual(len(cookiejar_2), 1)257 self.assertCookieHas(list(cookiejar_2)[0], name='Persistent', value='CookiesAreScary')258259260class MozCookieJarTest(LWPCookieJarTest):261 """Same test, but substitute MozillaCookieJar."""262263 COOKIEJAR_CLASS = cookielib.MozillaCookieJar
3 unmodified lines
modified:tests/test_requests_ext.py+3 added-11 removed
23 unmodified lines
2425 def test_addition(self):26 assert (1 + 1) == 2272828 def test_ssl_hostname_ok(self):29 requests.get('https://github.com', verify=True)303231 def test_ssl_hostname_not_ok(self):32 requests.get('https://kennethreitz.com', verify=False)3334 self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')353836 def test_ssl_hostname_session_not_ok(self):3738 s = requests.session()3940 self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')4142 s.get('https://kennethreitz.com', verify=False)434744 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 lines
54 else:55 raise EnvironmentError('Flesh out this test for your environment.')56 requests.post('http://www.google.com/', data=utf8_string)57626358 def test_unicode_error(self):59 url = 'http://blip.fm/~1abvfu'60 requests.get(url)616862 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 lines
102 # 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')110111 # 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'])115116 # 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'])121122if __name__ == '__main__':123 unittest.main()131
modified:tests/test_requests_https.py+1 added
7 unmodified lines
8# Path hack.9sys.path.insert(0, os.path.abspath('..'))10import requests111213class HTTPSTest(unittest.TestCase):14 """Smoke test for https functionality."""1516 smoke_url = "https://github.com"
16 unmodified lines
modified:tests/test_requests.py+90 added-3 removed
5 unmodified lines
6# Path hack.7import sys8import os9sys.path.insert(0, os.path.abspath('..'))1010import json11import os12import unittest13import pickle
4 unmodified lines
18# import envoy19from requests import HTTPError20from requests import get, post, head, put21from requests.auth import HTTPBasicAuth, HTTPDigestAuth22from requests.exceptions import InvalidURL2324if 'HTTPBIN_URL' not in os.environ:25 os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'26
828 unmodified lines
855 ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=False)))856 assert ds1.prefetch857 assert not ds2.prefetch858859 def test_connection_error(self):860 try:861 get('http://localhost:1/nope')862 except requests.ConnectionError:863 pass864 else:865 assert False866867 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 == None871872 # def test_invalid_content(self):873 # # WARNING: if you're using a terrible DNS provider (comcast),874 # # this will fail.875 # try:
155 unmodified lines
1031 """Test that it is possible to POST using the files argument and a1032 list for a value in the data argument."""10331034 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 lines
1047 r = post(httpbin('post'), data=data)1048 t = json.loads(r.text)1049 self.assertEqual(t.get('headers').get('Content-Type'), '')10501051 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('{'))10591060 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('{'))10671068 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'10791080 def __str__(self):1081 return 'http://httpbin.org/get'10821083 r = get(URL())1084 self.assertEqual(r.status_code, 200)10851086 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 """10911092 fields = [1093 ('__field__', '__value__'),1094 ('__field__', '__value__'),1095 ]10961097 r = post(httpbin('post'), data=fields, files=fields)1098 t = json.loads(r.text)10991100 self.assertEqual(t.get('form'), {1101 '__field__': [1102 '__value__',1103 '__value__',1104 ]1105 })11061107 # 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)11161117 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'})11201121 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/')11251126if __name__ == '__main__':1127 unittest.main()
modified:AUTHORS.rst+1 added
108 unmodified lines
109- Sarah Gonzalez110- Victoria Mo111- Leila Muhtasib112- Matthias Rahlf <matthias@webding.de>113- Jakub Roztocil <jakub@roztocil.name>