Skip to content
Myr

merge

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

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 599a8f1, 07372dc · Browse files · 25 files+381 added−78 removed
This commit

State

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

Diff stats

25 files+381 added−78 removed

  • tests:+150 added−6 removed
  • other:+231 added−72 removed

25 files+381 added−78 removed

modified:docs/_templates/sidebarintro.html+5 added-5 removed
modified:docs/_templates/sidebarlogo.html+2 added-2 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+1 added-1 removed
32 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----------------
26 unmodified lines
modified:docs/dev/todo.rst+1 added-1 removed
59 unmodified lines
6061Google AppEngine is not officially supported although support is available62with the `Requests-Toolbelt`_.6364.. _Requests-Toolbelt: http://toolbelt.readthedocs.io/64.. _Requests-Toolbelt: https://toolbelt.readthedocs.io/65
modified:docs/user/advanced.rst+29 added-5 removed
285 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:
140 unmodified lines
435You can assign a hook function on a per-request basis by passing a436``{hook_name: callback_function}`` dictionary to the ``hooks`` request437parameter::438439 hooks=dict(response=print_url)439 hooks={'response': print_url}440441That ``callback_function`` will receive a chunk of data as its first442argument.443
7 unmodified lines
451If the callback function returns a value, it is assumed that it is to452replace the data that was passed in. If the function doesn't return453anything, nothing else is effected.454455::456457 def record_hook(r, *args, **kwargs):458 r.hook_called = True459 return r460461Let's print some request method arguments at runtime::462457 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))463 >>> requests.get('http://httpbin.org', hooks={'response': print_url})464 http://httpbin.org465 <Response [200]>466467You can add multiple hooks to a single request. Let's call two hooks at once::468469 >>> r = requests.get('http://httpbin.org', hooks={'response': [print_url, record_hook]})470 >>> r.hook_called471 True472473You can also add hooks to a ``Session`` instance. Any hooks you add will then474be called on every request made to the session. For example::475476 >>> s = requests.Session()477 >>> s.hooks['response'].append(print_url)478 >>> s.get('http://httpbin.org')479 http://httpbin.org480 <Response [200]>481482A ``Session`` can have multiple hooks, which will be called in the order483they are added.484485.. _custom-auth:486487Custom Authentication488---------------------
167 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 `chardet636<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.886863GitHub 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/user/quickstart.rst+10 added-1 removed
108 unmodified lines
109110If you change the encoding, Requests will use the new value of ``r.encoding``111whenever you call ``r.text``. You might want to do this in any situation where112you can apply special logic to work out what the encoding of the content will113be. For example, HTTP and XML have the ability to specify their encoding in113be. For example, HTML and XML have the ability to specify their encoding in114their body. In situations like this, you should use ``r.content`` to find the115encoding, and then set ``r.encoding``. This will let you use ``r.text`` with116the correct encoding.117
70 unmodified lines
188download, the above is the preferred and recommended way to retrieve the189content. Note that ``chunk_size`` can be freely adjusted to a number that190may better fit your use cases.191192.. note::193194 An important note about using ``Response.iter_content`` versus ``Response.raw``.195 ``Response.iter_content`` will automatically decode the ``gzip`` and ``deflate``196 transfer-encodings. ``Response.raw`` is a raw stream of bytes -- it does not197 transform the response content. If you really need access to the bytes as they198 were returned, use ``Response.raw``.199200201Custom Headers202--------------203204If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the
75 unmodified lines
280 >>> payload = {'some': 'data'}281282 >>> r = requests.post(url, json=payload)283284Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.285286POST a Multipart-Encoded File287-----------------------------288
268 unmodified lines
modified:docs/api.rst+1 added-11 removed
107 unmodified lines
108------------------109110.. autoclass:: requests.codes111112::112.. automodule:: requests.status_codes113114 >>> requests.codes['temporary_redirect']115 307114117 >>> requests.codes.teapot118 418119120 >>> requests.codes['\o/']121 200122123124115Migrating to 1.x116----------------117118This section details the main differences between 0.x and 1.x and is meant
142 unmodified lines
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:requests/__init__.py+15 added
69 unmodified lines
70 assert minor < 171 assert patch >= 2727374def _check_cryptography(cryptography_version):75 # cryptography < 1.3.476 try:77 cryptography_version = list(map(int, cryptography_version.split('.')))78 except ValueError:79 return8081 if cryptography_version < [1, 3, 4]:82 warning = 'Old version of cryptography ({0}) may cause slowdown.'.format(cryptography_version)83 warnings.warn(warning, RequestsDependencyWarning)8485# Check imported dependencies for compatibility.86try:87 check_compatibility(urllib3.__version__, chardet.__version__)88except (AssertionError, ValueError):
4 unmodified lines
93# Attempt to enable urllib3's SNI support, if possible94try:95 from urllib3.contrib import pyopenssl96 pyopenssl.inject_into_urllib3()9798 # Check cryptography version99 from cryptography import __version__ as cryptography_version100 _check_cryptography(cryptography_version)101except ImportError:102 pass103104# urllib3's DependencyWarnings should be silenced.
32 unmodified lines
modified:requests/adapters.py+10 added-5 removed
11 unmodified lines
12import socket1314from urllib3.poolmanager import PoolManager, proxy_from_url15from urllib3.response import HTTPResponse16from urllib3.util import parse_url17from urllib3.util import Timeout as TimeoutSauce18from urllib3.util.retry import Retry19from urllib3.exceptions import ClosedPoolError20from urllib3.exceptions import ConnectTimeoutError
7 unmodified lines
28from urllib3.exceptions import ResponseError2930from .models import Response31from .compat import urlparse, basestring31from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,32 prepend_scheme_if_needed, get_auth_from_url, urldefragauth,33 select_proxy)32from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths,33 get_encoding_from_headers, prepend_scheme_if_needed,34 get_auth_from_url, urldefragauth, select_proxy)35from .structures import CaseInsensitiveDict36from .cookies import extract_cookies_to_jar37from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,37 ProxyError, RetryError, InvalidSchema)38 ProxyError, RetryError, InvalidSchema, InvalidProxyURL)39from .auth import _basic_auth_str4041try:42 from urllib3.contrib.socks import SOCKSProxyManager
176 unmodified lines
219 if verify is not True:220 cert_loc = verify221222 if not cert_loc:222 cert_loc = DEFAULT_CA_BUNDLE_PATH223 cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)224225 if not cert_loc or not os.path.exists(cert_loc):226 raise IOError("Could not find a suitable TLS CA certificate bundle, "227 "invalid path: {0}".format(cert_loc))
72 unmodified lines
300 proxy = select_proxy(url, proxies)301302 if proxy:303 proxy = prepend_scheme_if_needed(proxy, 'http')304 proxy_url = parse_url(proxy)305 if not proxy_url.host:306 raise InvalidProxyURL("Please check proxy URL. It is malformed"307 " and could be missing the host.")308 proxy_manager = self.proxy_manager_for(proxy)309 conn = proxy_manager.connection_from_url(url)310 else:311 # Only scheme should be lower case
219 unmodified lines
modified:requests/exceptions.py+4 added
83 unmodified lines
84class InvalidHeader(RequestException, ValueError):85 """The header value provided was somehow invalid."""868788class InvalidProxyURL(InvalidURL):89 """The proxy URL provided is invalid."""909192class ChunkedEncodingError(RequestException):93 """The server declared chunked encoding but sent an invalid chunk."""9495
31 unmodified lines
modified:requests/models.py+2 added-2 removed
684 unmodified lines
685 return self.iter_content(128)686687 @property688 def ok(self):689 """Returns True if :attr:`status_code` is less than 400.689 """Returns True if :attr:`status_code` is less than 400, False if not.690691 This attribute checks if the status code of the response is between692 400 and 600 to see if there was a client error or a server error. If693 the status code, is between 200 and 400, this will return True. This693 the status code is between 200 and 400, this will return True. This694 is **not** a check to see if the response code is ``200 OK``.695 """696 try:697 self.raise_for_status()
251 unmodified lines
modified:requests/sessions.py+4 added-4 removed
6 unmodified lines
7This module provides a Session object to manage and persist settings across8requests (cookies, auth, proxies).9"""10import os11import platform11import sys12import time13from collections import Mapping14from datetime import timedelta15
21 unmodified lines
37# formerly defined here, reexposed here for backward compatibility38from .models import REDIRECT_STATI3940# Preferred clock, based on which one is more accurate on a given system.41if platform.system() == 'Windows':42 try: # Python 3.3+41if sys.platform == 'win32':42 try: # Python 3.4+43 preferred_clock = time.perf_counter44 except AttributeError: # Earlier than Python 3.45 preferred_clock = time.clock46else:
648 unmodified lines
695 :rtype: requests.adapters.BaseAdapter696 """697 for (prefix, adapter) in self.adapters.items():698699 if url.lower().startswith(prefix):699 if url.lower().startswith(prefix.lower()):700 return adapter701702 # Nothing matches :-/703 raise InvalidSchema("No connection adapters were found for '%s'" % url)
34 unmodified lines
modified:requests/status_codes.py+33 added-5 removed
1# -*- coding: utf-8 -*-23"""4The ``codes`` object defines a mapping from common names for HTTP statuses5to their numerical codes, accessible either as attributes or as dictionary6items.78>>> requests.codes['temporary_redirect']930710>>> requests.codes.teapot1141812>>> requests.codes['\o/']132001415Some codes have multiple names, and both upper- and lower-case versions of16the names are allowed. For example, ``codes.ok``, ``codes.OK``, and17``codes.okay`` all correspond to the HTTP status code 200.18"""1920from .structures import LookupDict2122_codes = {23
76 unmodified lines
100}101102codes = LookupDict(name='status_codes')103104def _init():87for code, titles in _codes.items():88 for title in titles:89 setattr(codes, title, code)90 if not title.startswith(('\\', '/')):91 setattr(codes, title.upper(), code)105 for code, titles in _codes.items():106 for title in titles:107 setattr(codes, title, code)108 if not title.startswith(('\\', '/')):109 setattr(codes, title.upper(), code)110111 def doc(code):112 names = ', '.join('``%s``' % n for n in _codes[code])113 return '* %d: %s' % (code, names)114115 global __doc__116 __doc__ = (__doc__ + '\n' +117 '\n'.join(doc(code) for code in sorted(_codes)))118119_init()
modified:requests/utils.py+85 added-18 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 io15import os17import platform16import re17import socket18import struct19import sys20import tempfile21import warnings22import zipfile2324from .__version__ import __version__25from . import certs26# to_native_string is unused here, but imported here for backwards compatibility
12 unmodified lines
3940DEFAULT_CA_BUNDLE_PATH = certs.where()414242if platform.system() == 'Windows':43if sys.platform == 'win32':44 # provide a proxy_bypass version on Windows without DNS lookups4546 def proxy_bypass_registry(host):46 if is_py3:47 import winreg48 else:49 import _winreg as winreg47 try:48 if is_py3:49 import winreg50 else:51 import _winreg as winreg52 except ImportError:53 return False5455 try:56 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,57 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')58 # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it53 proxyEnable = winreg.QueryValueEx(internetSettings,54 'ProxyEnable')[0]59 proxyEnable = int(winreg.QueryValueEx(internetSettings,60 'ProxyEnable')[0])61 # ProxyOverride is almost always a string62 proxyOverride = winreg.QueryValueEx(internetSettings,63 'ProxyOverride')[0]64 except OSError:65 return False
156 unmodified lines
222 name[-1] != '>'):223 return os.path.basename(name)224225226def extract_zipped_paths(path):227 """Replace nonexistant 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):232 # this is already a valid path, no need to do anything further233 return path234235 # find the first valid part of the provided path and treat that as a zip archive236 # assume the rest of the path is the name of a member in the archive237 archive, member = os.path.split(path)238 while archive and not os.path.exists(archive):239 archive, prefix = os.path.split(archive)240 member = '/'.join([prefix, member])241242 if not zipfile.is_zipfile(archive):243 return path244245 zip_file = zipfile.ZipFile(archive)246 if member not in zip_file.namelist():247 return path248249 # we have a valid zip archive and a valid member of that archive250 tmp = tempfile.gettempdir()251 extracted_path = os.path.join(tmp, *member.split('/'))252 if not os.path.exists(extracted_path):253 extracted_path = zip_file.extract(member, path=tmp)254255 return extracted_path256257258def from_key_val_list(value):259 """Take an object and test to see if it can be represented as a260 dictionary. Unless it can not be represented as such, return an261 OrderedDict, e.g.,
183 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 None485422 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')642 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 match646 # 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 )714651 ip = netloc.split(':')[0]652 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):655 if address_in_network(ip, proxy_ip):718 if address_in_network(parsed.hostname, proxy_ip):719 return True657 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:663 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:676 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_requests.py+52 added-1 removed
21 unmodified lines
22 cookiejar_from_dict, morsel_to_cookie)23from requests.exceptions import (24 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,25 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,26 ProxyError, InvalidHeader, UnrewindableBodyError, SSLError)26 ProxyError, InvalidHeader, UnrewindableBodyError, SSLError, InvalidProxyURL)27from requests.models import PreparedRequest28from requests.structures import CaseInsensitiveDict29from requests.sessions import SessionRedirectMixin30from requests.models import urlencode
494 unmodified lines
525 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError526 with pytest.raises(ProxyError):527 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})528529 def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):530 with pytest.raises(InvalidProxyURL):531 requests.get(httpbin_secure(), proxies={'https': 'http:/badproxyurl:3128'})532533 with pytest.raises(InvalidProxyURL):534 requests.get(httpbin(), proxies={'http': 'http://:8080'})535536 with pytest.raises(InvalidProxyURL):537 requests.get(httpbin_secure(), proxies={'https': 'https://'})538539 with pytest.raises(InvalidProxyURL):540 requests.get(httpbin(), proxies={'http': 'http:///example.com:8080'})541542 def test_basicauth_with_netrc(self, httpbin):543 auth = ('user', 'pass')544 wrong_auth = ('wronguser', 'wrongpass')545 url = httpbin('basic-auth', 'user', 'pass')
817 unmodified lines
1363 s2.mount('https://', HTTPAdapter())1364 assert 'http://' in s2.adapters1365 assert 'https://' in s2.adapters13661367 def test_session_get_adapter_prefix_matching(self, httpbin):1368 prefix = 'https://example.com'1369 more_specific_prefix = prefix + '/some/path'13701371 url_matching_only_prefix = prefix + '/another/path'1372 url_matching_more_specific_prefix = more_specific_prefix + '/longer/path'1373 url_not_matching_prefix = 'https://another.example.com/'13741375 s = requests.Session()1376 prefix_adapter = HTTPAdapter()1377 more_specific_prefix_adapter = HTTPAdapter()1378 s.mount(prefix, prefix_adapter)1379 s.mount(more_specific_prefix, more_specific_prefix_adapter)13801381 assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1382 assert s.get_adapter(url_matching_more_specific_prefix) is more_specific_prefix_adapter1383 assert s.get_adapter(url_not_matching_prefix) not in (prefix_adapter, more_specific_prefix_adapter)13841385 def test_session_get_adapter_prefix_matching_mixed_case(self, httpbin):1386 mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1387 url_matching_prefix = mixed_case_prefix + '/full_url'13881389 s = requests.Session()1390 my_adapter = HTTPAdapter()1391 s.mount(mixed_case_prefix, my_adapter)13921393 assert s.get_adapter(url_matching_prefix) is my_adapter13941395 def test_session_get_adapter_prefix_matching_is_case_insensitive(self, httpbin):1396 mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1397 url_matching_prefix_with_different_case = 'HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url'13981399 s = requests.Session()1400 my_adapter = HTTPAdapter()1401 s.mount(mixed_case_prefix, my_adapter)14021403 assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter14041405 def test_header_remove_is_case_insensitive(self, httpbin):1406 # From issue #13211407 s = requests.Session()1408 s.headers['foo'] = 'bar'
1032 unmodified lines
modified:tests/test_utils.py+98 added-5 removed
1# -*- coding: utf-8 -*-23import os4import copy5import filecmp6from io import BytesIO7import zipfile8from collections import deque910import pytest11from requests import compat12from requests.cookies import RequestsCookieJar13from requests.structures import CaseInsensitiveDict14from requests.utils import (12 address_in_network, dotted_netmask,13 get_auth_from_url, get_encoding_from_headers,15 address_in_network, dotted_netmask, extract_zipped_paths,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,
237 unmodified lines
258 assert result == value259 assert isinstance(result, expected_type)260261262class TestExtractZippedPaths:263264 @pytest.mark.parametrize(265 'path', (266 '/',267 __file__,268 pytest.__file__,269 '/etc/invalid/location',270 ))271 def test_unzipped_paths_unchanged(self, path):272 assert path == extract_zipped_paths(path)273274 def test_zipped_paths_extracted(self, tmpdir):275 zipped_py = tmpdir.join('test.zip')276 with zipfile.ZipFile(zipped_py.strpath, 'w') as f:277 f.write(__file__)278279 _, name = os.path.splitdrive(__file__)280 zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r'\/'))281 extracted_path = extract_zipped_paths(zipped_path)282283 assert extracted_path != zipped_path284 assert os.path.exists(extracted_path)285 assert filecmp.cmp(extracted_path, __file__)286287288class TestContentEncodingDetection:289290 def test_none(self):291 encodings = get_encodings_from_content('')
180 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 """557 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')558 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 ))
70 unmodified lines
726 def Close(self):727 pass728729 ie_settings = RegHandle()730 proxyEnableValues = deque([1, "1"])731732 def OpenKey(key, subkey):733 return ie_settings734735 def QueryValueEx(key, value_name):736 if key is ie_settings:737 if value_name == 'ProxyEnable':648 return [1]738 # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)739 proxyEnableValues.rotate()740 return [proxyEnableValues[0]]741 elif value_name == 'ProxyOverride':742 return [override]743744 monkeypatch.setenv('http_proxy', '')
2 unmodified lines
747 monkeypatch.setenv('no_proxy', '')748 monkeypatch.setenv('NO_PROXY', '')749 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)750 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)751 assert should_bypass_proxies(url, None) == expected752753754@pytest.mark.parametrize(755 'env_name, value', (
22 unmodified lines
modified:AUTHORS.rst+5 added
176 unmodified lines
177- Gary Wu (`@garywu <https://github.com/garywu>`_)178- Ryan Pineo (`@ryanpineo <https://github.com/ryanpineo>`_)179- Ed Morley (`@edmorley <https://github.com/edmorley>`_)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+8 added
6 unmodified lines
7+++89**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.1314**Bugfixes**1516- Parsing empty ``Link`` headers with ``parse_header_links()`` no longer return one bogus entry17- Fixed issue where loading the default certificate bundle from a zip archive18 would raise an ``IOError``19- Fixed issue with unexpected ``ImportError`` on windows system which do not support ``winreg`` module20- DNS resolution in proxy bypass no longer includes the username and password in21 the request. This also fixes the issue of DNS queries failing on macOS.22232.18.4 (2017-08-15)24+++++++++++++++++++25
1519 unmodified lines
modified:README.rst+2 added-2 removed
75 unmodified lines
76- Streaming Downloads77- ``.netrc`` Support78- Chunked Requests7980Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy.80Requests officially supports Python 2.6–2.7 & 3.4–3.6, and runs great on PyPy.8182Installation83------------84
19 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.cfg+3 added
1[bdist_wheel]2universal = 134[metadata]5license_file = LICENSE
modified:setup.py+2 added-1 removed
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=(
1 unmodified line
81 'Intended Audience :: Developers',82 'Natural Language :: English',83 'License :: OSI Approved :: Apache Software License',84 'Programming Language :: Python',85 'Programming Language :: Python :: 2',86 'Programming Language :: Python :: 2.6',87 'Programming Language :: Python :: 2.7',88 'Programming Language :: Python :: 3',89 'Programming Language :: Python :: 3.4',
9 unmodified lines
99 'socks': ['PySocks>=1.5.6, !=1.5.7'],100 'socks:sys_platform == "win32" and (python_version == "2.7" or python_version == "2.6")': ['win_inet_pton'],101 },102)101
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