Skip to content
Myr

Merge branch 'master' of github.com:requests/requests

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

# Conflicts: # docs/_templates/sidebarintro.html # docs/_templates/sidebarlogo.html

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 3cd87fa, 22120d4 · Browse files · 22 files+228 added−58 removed
This commit

State

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

Trailers

  • Signed-off-by: Kenneth Reitz <me@kennethreitz.org>

Diff stats

22 files+228 added−58 removed

  • tests:+143 added−3 removed
  • other:+85 added−55 removed

22 files+228 added−58 removed

modified:docs/_templates/sidebarintro.html+6 added-6 removed
modified:docs/_templates/sidebarlogo.html+3 added-3 removed
modified:docs/community/out-there.rst+1 added-1 removed
16 unmodified lines
17================18- `Python for the Web <http://gun.io/blog/python-for-the-web/>`_ teaches how to use Python to interact with the web, using Requests.19- `Daniel Greenfeld's Review of Requests <http://pydanny.blogspot.com/2011/05/python-http-requests-for-humans.html>`_20- `My 'Python for Humans' talk <http://python-for-humans.heroku.com>`_ ( `audio <http://codeconf.s3.amazonaws.com/2011/pycodeconf/talks/PyCodeConf2011%20-%20Kenneth%20Reitz.m4a>`_ )21- `Issac Kelly's 'Consuming Web APIs' talk <http://issackelly.github.com/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_21- `Issac Kelly's 'Consuming Web APIs' talk <https://issackelly.github.com/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_22- `Blog post about Requests via Yum <http://arunsag.wordpress.com/2011/08/17/new-package-python-requests-http-for-humans/>`_23- `Russian blog post introducing Requests <http://habrahabr.ru/blogs/python/126262/>`_24- `Sending JSON in Requests <http://www.coglib.com/~icordasc/blog/2014/11/sending-json-in-requests.html>`_
modified:docs/community/recommended.rst+2 added-5 removed
13 unmodified lines
14`Certifi`_ is a carefully curated collection of Root Certificates for15validating the trustworthiness of SSL certificates while verifying the16identity of TLS hosts. It has been extracted from the Requests project.1718.. _Certifi: http://certifi.io/en/latest/18.. _Certifi: https://github.com/certifi/python-certifi1920CacheControl21------------22
10 unmodified lines
33but do not belong in Requests proper. This library is actively maintained34by members of the Requests core team, and reflects the functionality most35requested by users within the community.3637.. _Requests-Toolbelt: http://toolbelt.readthedocs.io/en/latest/index.html37.. _Requests-Toolbelt: https://toolbelt.readthedocs.io/en/latest/index.html383940Requests-Threads41----------------
19 unmodified lines
61`Betamax`_ records your HTTP interactions so the NSA does not have to.62A VCR imitation designed only for Python-Requests.6364.. _betamax: https://github.com/sigmavirus24/betamax656667
modified:docs/community/updates.rst-1 removed
27 unmodified lines
28Release and Version History29===========================3031.. include:: ../../HISTORY.rst32
modified:docs/dev/todo.rst+1 added-2 removed
59 unmodified lines
6061Google AppEngine is not officially supported although support is available62with the `Requests-Toolbelt`_.6364.. _Requests-Toolbelt: http://toolbelt.readthedocs.io/6564.. _Requests-Toolbelt: https://toolbelt.readthedocs.io/
modified:docs/user/advanced.rst+8 added-8 removed
194 unmodified lines
195As a result an ``SSL: CERTIFICATE_VERIFY_FAILED`` is thrown.196You can get around this behaviour by explicity merging the environment settings into your session::197198 from requests import Request, Session199 199200 s = Session()201 req = Request('GET', url)202 202203 prepped = s.prepare_request(req)204 204205 # Merge environment settings into session206 settings = s.merge_environment_settings(prepped.url, None, None, None, None)207 resp = s.send(prepped, **settings)208 208209 print(resp.status_code)210 210211.. _verification:212213SSL Cert Verification214---------------------
71 unmodified lines
286287For the sake of security we recommend upgrading certifi frequently!288289.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection290.. _connection pooling: http://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool290.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool291.. _certifi: http://certifi.io/292.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt293294.. _body-content-workflow:
361 unmodified lines
656When you receive a response, Requests makes a guess at the encoding to657use for decoding the response when you access the :attr:`Response.text658<requests.Response.text>` attribute. Requests will first check for an659encoding in the HTTP header, and if none is present, will use `chardet660<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.660<https://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.661662The only time Requests will not do this is if no explicit charset663is present in the HTTP headers **and** the ``Content-Type``664header contains ``text``. In this situation, `RFC 2616
218 unmodified lines
883884Many HTTP APIs feature Link headers. They make APIs more self describing and885discoverable.886887GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_887GitHub uses these for `pagination <https://developer.github.com/v3/#pagination>`_888in their API, for example::889890 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'891 >>> r = requests.head(url=url)
145 unmodified lines
modified:docs/user/authentication.rst+5 added-5 removed
134 unmodified lines
135``auth.py`` file.136137.. _OAuth: http://oauth.net/138.. _requests_oauthlib: https://github.com/requests/requests-oauthlib139.. _requests-oauthlib OAuth2 documentation: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html140.. _Web Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#web-application-flow141.. _Mobile Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#mobile-application-flow142.. _Legacy Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#legacy-application-flow143.. _Backend Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow139.. _requests-oauthlib OAuth2 documentation: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html140.. _Web Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#web-application-flow141.. _Mobile Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#mobile-application-flow142.. _Legacy Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#legacy-application-flow143.. _Backend Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow144.. _Kerberos: https://github.com/requests/requests-kerberos145.. _NTLM: https://github.com/requests/requests-ntlm146.. _Requests organization: https://github.com/requests
modified:docs/conf.py+1 added-1 removed
374 unmodified lines
375376# If false, no index is generated.377#epub_use_index = True378379intersphinx_mapping = {'urllib3': ('http://urllib3.readthedocs.io/en/latest', None)}379intersphinx_mapping = {'urllib3': ('https://urllib3.readthedocs.io/en/latest', None)}
modified:docs/index.rst+2 added-2 removed
28 unmodified lines
29consumption.3031.. note:: The use of **Python 3** is *highly* preferred over Python 2. Consider upgrading your applications and infrastructure if you find yourself *still* using Python 2 in production today. If you are using Python 3, congratulations — you are indeed a person of excellent taste.32 —*Kenneth Reitz*33 34 333435-------------------3637**Behold, the power of Requests**::38
133 unmodified lines
modified:requests/adapters.py+1 added-1 removed
409 unmodified lines
410 conn = self.get_connection(request.url, proxies)411412 self.cert_verify(conn, request.url, verify, cert)413 url = self.request_url(request, proxies)414 self.add_headers(request)414 self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)415416 chunked = not (request.body is None or 'Content-Length' in request.headers)417418 if isinstance(timeout, tuple):
112 unmodified lines
modified:requests/sessions.py+6 added-1 removed
121 unmodified lines
122123 hist = [] # keep track of history124125 url = self.get_redirect_target(resp)126 previous_fragment = urlparse(req.url).fragment127 while url:128 prepared_request = req.copy()129130 # Update history and keep track of redirects.
16 unmodified lines
147 if url.startswith('//'):148 parsed_rurl = urlparse(resp.url)149 url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)150150 # The scheme should be lower case...151 # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)152 parsed = urlparse(url)153 if parsed.fragment == '' and previous_fragment:154 parsed = parsed._replace(fragment=previous_fragment)155 elif parsed.fragment:156 previous_fragment = parsed.fragment157 url = parsed.geturl()158159 # Facilitate relative 'location' headers, as allowed by RFC 7231.160 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
582 unmodified lines
modified:requests/utils.py+38 added-11 removed
6 unmodified lines
7This module provides utility functions that are used within Requests8that are also useful for external consumption.9"""1011import cgi11import codecs12import collections13import contextlib14import io
208 unmodified lines
223 return os.path.basename(name)224225226def extract_zipped_paths(path):228 """Replace nonexistant paths that look like they refer to a member of a zip227 """Replace nonexistent paths that look like they refer to a member of a zip228 archive with the location of an extracted copy of the target, or else229 just return the provided path unchanged.230 """231 if os.path.exists(path):
213 unmodified lines
445 pragma_re.findall(content) +446 xml_re.findall(content))447448449def _parse_content_type_header(header):450 """Returns content type and parameters from given header451452 :param header: string453 :return: tuple containing content type and dictionary of454 parameters455 """456457 tokens = header.split(';')458 content_type, params = tokens[0].strip(), tokens[1:]459 params_dict = {}460 items_to_strip = "\"' "461462 for param in params:463 param = param.strip()464 if param:465 key, value = param, True466 index_of_equals = param.find("=")467 if index_of_equals != -1:468 key = param[:index_of_equals].strip(items_to_strip)469 value = param[index_of_equals + 1:].strip(items_to_strip)470 params_dict[key] = value471 return content_type, params_dict472473474def get_encoding_from_headers(headers):475 """Returns encodings from given HTTP Header Dict.476477 :param headers: dictionary to extract encoding from.
4 unmodified lines
482483 if not content_type:484 return None485462 content_type, params = cgi.parse_header(content_type)486 content_type, params = _parse_content_type_header(content_type)487488 if 'charset' in params:489 return params['charset'].strip("'\"")490
211 unmodified lines
702 # we're getting isn't in the no_proxy list.703 no_proxy_arg = no_proxy704 if no_proxy is None:705 no_proxy = get_proxy('no_proxy')682 netloc = urlparse(url).netloc706 parsed = urlparse(url)707708 if no_proxy:709 # We need to check whether we match here. We need to see if we match686 # the end of the netloc, both with and without the port.710 # the end of the hostname, both with and without the port.711 no_proxy = (712 host for host in no_proxy.replace(' ', '').split(',') if host713 )714691 ip = netloc.split(':')[0]692 if is_ipv4_address(ip):715 if is_ipv4_address(parsed.hostname):716 for proxy_ip in no_proxy:717 if is_valid_cidr(proxy_ip):695 if address_in_network(ip, proxy_ip):718 if address_in_network(parsed.hostname, proxy_ip):719 return True697 elif ip == proxy_ip:720 elif parsed.hostname == proxy_ip:721 # If no_proxy ip was defined in plain IP notation instead of cidr notation &722 # matches the IP of the index723 return True724 else:725 host_with_port = parsed.hostname726 if parsed.port:727 host_with_port += ':{0}'.format(parsed.port)728729 for host in no_proxy:703 if netloc.endswith(host) or netloc.split(':')[0].endswith(host):730 if parsed.hostname.endswith(host) or host_with_port.endswith(host):731 # The URL does match something in no_proxy, so we don't want732 # to apply the proxies on this URL.733 return True734
4 unmodified lines
739 # exceptions we've seen, though: this call failing in other ways can reveal740 # legitimate problems.741 with set_environ('no_proxy', no_proxy_arg):742 try:716 bypass = proxy_bypass(netloc)743 bypass = proxy_bypass(parsed.hostname)744 except (TypeError, socket.gaierror):745 bypass = False746747 if bypass:
228 unmodified lines
modified:tests/test_lowlevel.py+72 added
233 unmodified lines
234 assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')235 assert r.url == u'{0}/{1}'.format(url, expected_path.decode('ascii'))236237 close_server.set()238239def test_fragment_not_sent_with_request():240 """Verify that the fragment portion of a URI isn't sent to the server."""241 def response_handler(sock):242 req = consume_socket_content(sock, timeout=0.5)243 sock.send(244 b'HTTP/1.1 200 OK\r\n'245 b'Content-Length: '+bytes(len(req))+b'\r\n'246 b'\r\n'+req247 )248249 close_server = threading.Event()250 server = Server(response_handler, wait_to_close_event=close_server)251252 with server as (host, port):253 url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)254 r = requests.get(url)255 raw_request = r.content256257 assert r.status_code == 200258 headers, body = raw_request.split(b'\r\n\r\n', 1)259 status_line, headers = headers.split(b'\r\n', 1)260261 assert status_line == b'GET /path/to/thing/ HTTP/1.1'262 for frag in (b'view', b'edit', b'token', b'hunter2'):263 assert frag not in headers264 assert frag not in body265266 close_server.set()267268def test_fragment_update_on_redirect():269 """Verify we only append previous fragment if one doesn't exist on new270 location. If a new fragment is encounterd in a Location header, it should271 be added to all subsequent requests.272 """273274 def response_handler(sock):275 consume_socket_content(sock, timeout=0.5)276 sock.send(277 b'HTTP/1.1 302 FOUND\r\n'278 b'Content-Length: 0\r\n'279 b'Location: /get#relevant-section\r\n\r\n'280 )281 consume_socket_content(sock, timeout=0.5)282 sock.send(283 b'HTTP/1.1 302 FOUND\r\n'284 b'Content-Length: 0\r\n'285 b'Location: /final-url/\r\n\r\n'286 )287 consume_socket_content(sock, timeout=0.5)288 sock.send(289 b'HTTP/1.1 200 OK\r\n\r\n'290 )291292 close_server = threading.Event()293 server = Server(response_handler, wait_to_close_event=close_server)294295 with server as (host, port):296 url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)297 r = requests.get(url)298 raw_request = r.content299300 assert r.status_code == 200301 assert len(r.history) == 2302 assert r.history[0].request.url == url303304 # Verify we haven't overwritten the location with our previous fragment.305 assert r.history[1].request.url == 'http://{0}:{1}/get#relevant-section'.format(host, port)306 # Verify previous fragment is used and not the original.307 assert r.url == 'http://{0}:{1}/final-url/#relevant-section'.format(host, port)308309 close_server.set()
modified:tests/test_requests.py+8 added
292 unmodified lines
293 assert next_resp.request.body is None294 for header in purged_headers:295 assert header not in next_resp.request.headers296297 def test_fragment_maintained_on_redirect(self, httpbin):298 fragment = "#view=edit&token=hunter2"299 r = requests.get(httpbin('redirect-to?url=get')+fragment)300301 assert len(r.history) > 0302 assert r.history[0].request.url == httpbin('redirect-to?url=get')+fragment303 assert r.url == httpbin('get')+fragment304305 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):306 heads = {'User-agent': 'Mozilla/5.0'}307308 r = requests.get(httpbin('user-agent'), headers=heads)
2140 unmodified lines
modified:tests/test_utils.py+63 added-3 removed
11 unmodified lines
12from requests.cookies import RequestsCookieJar13from requests.structures import CaseInsensitiveDict14from requests.utils import (15 address_in_network, dotted_netmask, extract_zipped_paths,16 get_auth_from_url, get_encoding_from_headers,16 get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,17 get_encodings_from_content, get_environ_proxies,18 guess_filename, guess_json_utf, is_ipv4_address,19 is_valid_cidr, iter_slices, parse_dict_header,20 parse_header_links, prepend_scheme_if_needed,
451 unmodified lines
472473@pytest.mark.parametrize(474 'value, expected', (475 (476 'application/xml',477 ('application/xml', {})478 ),479 (480 'application/json ; charset=utf-8',481 ('application/json', {'charset': 'utf-8'})482 ),483 (484 'text/plain',485 ('text/plain', {})486 ),487 (488 'multipart/form-data; boundary = something ; boundary2=\'something_else\' ; no_equals ',489 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})490 ),491 (492 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',493 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})494 ),495 (496 'multipart/form-data; boundary = something ; \'boundary2=something_else\' ; no_equals ',497 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})498 ),499 (500 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',501 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})502 ),503 (504 'application/json ; ; ',505 ('application/json', {})506 )507 ))508def test__parse_content_type_header(value, expected):509 assert _parse_content_type_header(value) == expected510511512@pytest.mark.parametrize(513 'value, expected', (514 (515 CaseInsensitiveDict(),516 None517 ),518 (
94 unmodified lines
613 ('http://192.168.0.1/', True),614 ('http://172.16.1.1/', True),615 ('http://172.16.1.1:5000/', True),616 ('http://localhost.localdomain:5000/v1.0/', True),617 ('http://google.com:6000/', True),618 ('http://172.16.1.12/', False),619 ('http://172.16.1.12:5000/', False),620 ('http://google.com:5000/v1.0/', False),621 ))622def test_should_bypass_proxies(url, expected, monkeypatch):623 """Tests for function should_bypass_proxies to check if proxy624 can be bypassed or not625 """586 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')587 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')626 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')627 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')628 assert should_bypass_proxies(url, no_proxy=None) == expected629630631@pytest.mark.parametrize(632 'url, expected', (633 ('http://172.16.1.1/', '172.16.1.1'),634 ('http://172.16.1.1:5000/', '172.16.1.1'),635 ('http://user:pass@172.16.1.1', '172.16.1.1'),636 ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),637 ('http://hostname/', 'hostname'),638 ('http://hostname:5000/', 'hostname'),639 ('http://user:pass@hostname', 'hostname'),640 ('http://user:pass@hostname:5000', 'hostname'),641 ))642def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):643 """The proxy_bypass function should be called with a hostname or IP without644 a port number or auth credentials.645 """646 proxy_bypass = mocker.patch('requests.utils.proxy_bypass')647 should_bypass_proxies(url, no_proxy=None)648 proxy_bypass.assert_called_once_with(expected)649650651@pytest.mark.parametrize(652 'cookiejar', (653 compat.cookielib.CookieJar(),654 RequestsCookieJar()655 ))
122 unmodified lines
modified:.travis.yml+1 added-3 removed
4 unmodified lines
5 - "2.7"6 - "3.4"7 - "3.5"8 - "3.6"9 # - "3.7-dev"9 - "3.7-dev"10 # - "pypy" -- appears to hang11 # - "pypy3"12# command to install dependencies13install: "make"
12 unmodified lines
26 - make ci27 - stage: coverage28 python: 3.629 script: codecov3031
modified:AUTHORS.rst+2 added
179 unmodified lines
180- Matt Liu <liumatt@gmail.com> (`@mlcrazy <https://github.com/mlcrazy>`_)181- Taylor Hoff <primdevs@protonmail.com> (`@PrimordialHelios <https://github.com/PrimordialHelios>`_)182- Arthur Vigil (`@ahvigil <https://github.com/ahvigil>`_)183- Nehal J Wani (`@nehaljwani <https://github.com/nehaljwani>`_)184- Demetrios Bairaktaris (`@DemetriosBairaktaris <https://github.com/demetriosbairaktaris>`_)185- Darren Dormer (`@ddormer <https://github.com/ddormer>`_)
modified:HISTORY.rst+4 added-2 removed
8 unmodified lines
9**Improvements**1011- Warn user about possible slowdown when using cryptography version < 1.3.412- Check for invalid host in proxy URL, before forwarding request to adapter.13- Fragments are now properly maintained across redirects. (RFC7231 7.1.2)1415**Bugfixes**1617- Parsing empty ``Link`` headers with ``parse_header_links()`` no longer return one bogus entry18- Fixed issue where loading the default certificate bundle from a zip archive19 would raise an ``IOError``20- Fixed issue with unexpected ``ImportError`` on windows system which do not support ``winreg`` module21- DNS resolution in proxy bypass no longer includes the username and password in22 the request. This also fixes the issue of DNS queries failing on macOS.2321242.18.4 (2017-08-15)25+++++++++++++++++++2627**Improvements**
102 unmodified lines
130+++++++++++++++++++131132- Further restored the ``requests.packages`` namespace for compatibility reasons.133132No code modification (noted below) should be neccessary any longer.134No code modification (noted below) should be necessary any longer.1351362.16.1 (2017-05-27)137+++++++++++++++++++138
1407 unmodified lines
modified:README.rst+1 added-1 removed
103 unmodified lines
104#. Fork `the repository`_ on GitHub to start making your changes to the **master** branch (or branch off of it).105#. Write a test which shows that the bug was fixed or that the feature works as expected.106#. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to AUTHORS_.107108.. _`the repository`: http://github.com/requests/requests108.. _`the repository`: https://github.com/requests/requests109.. _AUTHORS: https://github.com/requests/requests/blob/master/AUTHORS.rst110.. _Contributor Friendly: https://github.com/requests/requests/issues?direction=desc&labels=Contributor+Friendly&page=1&sort=updated&state=open
modified:setup.py+1 added
70 unmodified lines
71 packages=packages,72 package_data={'': ['LICENSE', 'NOTICE'], 'requests': ['*.pem']},73 package_dir={'requests': 'requests'},74 include_package_data=True,75 python_requires=">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",76 install_requires=requires,77 license=about['__license__'],78 zip_safe=False,79 classifiers=(
23 unmodified lines
modified:tox.ini+2 added-2 removed
1[tox]2envlist = py26,py27,py33,py34,py35,py362envlist = py26,py27,py34,py35,py3634[testenv]56commands =7 pip install -e .[socks]8 python setup.py test8 python setup.py test