Skip to content
Myr

Merge pull request #3429 from nateprewitt/docstring_cleanup

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

Docstring cleanup

authored by Kenneth Reitz · committed by GitHub · parents 4285bac, b7809ac · Browse files · 22 files+130 added−108 removed
This commit

State

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

Diff stats

22 files+130 added−108 removed

  • tests:+30 added−26 removed
  • other:+100 added−82 removed

22 files+130 added−108 removed

modified:requests/__init__.py-1 removed
36 unmodified lines
37is at <http://python-requests.org>.3839:copyright: (c) 2016 by Kenneth Reitz.40:license: Apache 2.0, see LICENSE for more details.4141"""4243__title__ = 'requests'44__version__ = '2.10.0'
42 unmodified lines
modified:requests/api.py-1 removed
6 unmodified lines
7This module implements the Requests API.89:copyright: (c) 2012 by Kenneth Reitz.10:license: Apache2, see LICENSE for more details.1111"""1213from . import sessions14
134 unmodified lines
modified:requests/certs.py+2 added-2 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""5certs.py6~~~~~~~~5requests.certs6~~~~~~~~~~~~~~78This module returns the preferred default CA certificate bundle.910If you are packaging Requests, e.g., for a Linux distribution or a managed
15 unmodified lines
modified:requests/compat.py+5 added-1 removed
1# -*- coding: utf-8 -*-23"""4pythoncompat4requests.compat5~~~~~~~~~~~~~~~67This module handles import compatibility issues between Python 2 and8Python 3.9"""1011from .packages import chardet12
54 unmodified lines
modified:requests/cookies.py+65 added-27 removed
1# -*- coding: utf-8 -*-23"""4requests.cookies5~~~~~~~~~~~~~~~~67Compatibility code to be able to use `cookielib.CookieJar` with requests.89requests.utils imports from here, so be careful with imports.10"""
149 unmodified lines
160161162class CookieConflictError(RuntimeError):163 """There are two cookies that meet the criteria specified in the cookie jar.161 Use .get and .set and include domain and path args in order to be more specific."""164 Use .get and .set and include domain and path args in order to be more specific.165 """166167168class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):169 """Compatibility class; is a cookielib.CookieJar, but exposes a dict
17 unmodified lines
187 """Dict-like get() that also supports optional domain and path args in188 order to resolve naming collisions from using one cookie jar over189 multiple domains.190187 .. warning:: operation is O(n), not O(1)."""191 .. warning:: operation is O(n), not O(1).192 """193 try:194 return self._find_no_duplicates(name, domain, path)195 except KeyError:196 return default197198 def set(self, name, value, **kwargs):199 """Dict-like set() that also supports optional domain and path args in200 order to resolve naming collisions from using one cookie jar over196 multiple domains."""201 multiple domains.202 """203 # support client code that unsets cookies by assignment of a None value:204 if value is None:205 remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))206 return
6 unmodified lines
213 return c214215 def iterkeys(self):216 """Dict-like iterkeys() that returns an iterator of names of cookies211 from the jar. See itervalues() and iteritems()."""217 from the jar.218219 .. seealso:: itervalues() and iteritems().220 """221 for cookie in iter(self):222 yield cookie.name223224 def keys(self):225 """Dict-like keys() that returns a list of names of cookies from the217 jar. See values() and items()."""226 jar.227228 .. seealso:: values() and items().229 """230 return list(self.iterkeys())231232 def itervalues(self):233 """Dict-like itervalues() that returns an iterator of values of cookies222 from the jar. See iterkeys() and iteritems()."""234 from the jar.235236 .. seealso:: iterkeys() and iteritems().237 """238 for cookie in iter(self):239 yield cookie.value240241 def values(self):242 """Dict-like values() that returns a list of values of cookies from the228 jar. See keys() and items()."""243 jar.244245 .. seealso:: keys() and items().246 """247 return list(self.itervalues())248249 def iteritems(self):250 """Dict-like iteritems() that returns an iterator of name-value tuples233 from the jar. See iterkeys() and itervalues()."""251 from the jar.252253 .. seealso:: iterkeys() and itervalues().254 """255 for cookie in iter(self):256 yield cookie.name, cookie.value257258 def items(self):259 """Dict-like items() that returns a list of name-value tuples from the239 jar. See keys() and values(). Allows client-code to call240 ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value241 pairs."""260 jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a261 vanilla python dict of key value pairs.262263 .. seealso:: keys() and values().264 """265 return list(self.iteritems())266267 def list_domains(self):268 """Utility method to list all the domains in the jar."""
12 unmodified lines
281 return paths282283 def multiple_domains(self):284 """Returns True if there are multiple domains in the jar.262 Returns False otherwise."""285 Returns False otherwise.286 """287 domains = []288 for cookie in iter(self):289 if cookie.domain is not None and cookie.domain in domains:290 return True
2 unmodified lines
293294 def get_dict(self, domain=None, path=None):295 """Takes as an argument an optional domain and path and returns a plain296 old Python dict of name-value pairs of cookies that meet the273 requirements."""297 requirements.298 """299 dictionary = {}300 for cookie in iter(self):301 if (domain is None or cookie.domain == domain) and (path is None302 or cookie.path == path):
10 unmodified lines
313 """Dict-like __getitem__() for compatibility with client code. Throws314 exception if there are more than one cookie with name. In that case,315 use the more explicit get() method instead.316292 .. warning:: operation is O(n), not O(1)."""293317 .. warning:: operation is O(n), not O(1).318 """319 return self._find_no_duplicates(name)320321 def __setitem__(self, name, value):322 """Dict-like __setitem__ for compatibility with client code. Throws323 exception if there is already a cookie of that name in the jar. In that299 case, use the more explicit set() method instead."""300324 case, use the more explicit set() method instead.325 """326 self.set(name, value)327328 def __delitem__(self, name):329 """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s305 ``remove_cookie_by_name()``."""330 ``remove_cookie_by_name()``.331 """332 remove_cookie_by_name(self, name)333334 def set_cookie(self, cookie, *args, **kwargs):335 if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
8 unmodified lines
344 else:345 super(RequestsCookieJar, self).update(other)346347 def _find(self, name, domain=None, path=None):322 """Requests uses this method internally to get cookie values. Takes as323 args name and optional domain and path. Returns a cookie.value. If324 there are conflicting cookies, _find arbitrarily chooses one. See325 _find_no_duplicates if you want an exception thrown if there are326 conflicting cookies."""348 """Requests uses this method internally to get cookie values.349350 If there are conflicting cookies, _find arbitrarily chooses one.351 See _find_no_duplicates if you want an exception thrown if there are352 conflicting cookies.353354 :param name: a string containing name of cookie355 :param domain: (optional) string containing domain of cookie356 :param path: (optional) string containing path of cookie357 :return: cookie.value358 """359 for cookie in iter(self):360 if cookie.name == name:361 if domain is None or cookie.domain == domain:362 if path is None or cookie.path == path:
2 unmodified lines
365 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))366367 def _find_no_duplicates(self, name, domain=None, path=None):368 """Both ``__get_item__`` and ``get`` call this function: it's never337 used elsewhere in Requests. Takes as args name and optional domain and338 path. Returns a cookie.value. Throws KeyError if cookie is not found339 and CookieConflictError if there are multiple cookies that match name340 and optionally domain and path."""369 used elsewhere in Requests.370371 :param name: a string containing name of cookie372 :param domain: (optional) string containing domain of cookie373 :param path: (optional) string containing path of cookie374 :raises KeyError: if cookie is not found375 :raises CookieConflictError: if there are multiple cookies376 that match name and optionally domain and path377 :return: cookie.value378 """379 toReturn = None380 for cookie in iter(self):381 if cookie.name == name:382 if domain is None or cookie.domain == domain:
150 unmodified lines
modified:requests/exceptions.py+4 added-8 removed
3 unmodified lines
4requests.exceptions5~~~~~~~~~~~~~~~~~~~67This module contains the set of Requests' exceptions.88"""9from .packages.urllib3.exceptions import HTTPError as BaseHTTPError101112class RequestException(IOError):13 """There was an ambiguous exception that occurred while handling your15 request."""14 request.15 """1617 def __init__(self, *args, **kwargs):18 """19 Initialize RequestException with `request` and `response` objects.20 """18 """Initialize RequestException with `request` and `response` objects."""19 response = kwargs.pop('response', None)20 self.response = response21 self.request = kwargs.pop('request', None)22 if (response is not None and not self.request and
86 unmodified lines
109 pass110111112class FileModeWarning(RequestsWarning, DeprecationWarning):115 """116 A file was opened in text mode, but Requests determined its binary length.117 """113 """A file was opened in text mode, but Requests determined its binary length."""114 pass
modified:requests/hooks.py-1 removed
8 unmodified lines
9Available hooks:1011``response``:12 The response generated from a Request.1313"""14HOOKS = ['response']1516
18 unmodified lines
modified:requests/models.py+2 added-5 removed
106 unmodified lines
107 tuples. Order is retained if data is a list of tuples but arbitrary108 if parameters are supplied as a dict.109 The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)110 or 4-tuples (filename, fileobj, contentype, custom_headers).111111 """112 if (not files):113 raise ValueError("Files must be provided.")114 elif isinstance(data, basestring):
90 unmodified lines
205 >>> import requests206 >>> req = requests.Request('GET', 'http://httpbin.org/get')207 >>> req.prepare()208 <PreparedRequest [GET]>210209 """210211 def __init__(self, method=None, url=None, headers=None, files=None,212 data=None, params=None, auth=None, cookies=None, hooks=None, json=None):
55 unmodified lines
268269 >>> s = requests.Session()270 >>> s.send(r)271 <Response [200]>274272 """273274 def __init__(self):275 #: HTTP verb to send to the server.
237 unmodified lines
513 will not be regenerated if it already exists, meaning this function514 can only be called once for the life of the515 :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls516 to ``prepare_cookies`` will have no actual effect, unless the "Cookie"520 header is removed beforehand."""521517 header is removed beforehand.518 """519 if isinstance(cookies, cookielib.CookieJar):520 self._cookies = cookies521 else:522 self._cookies = cookiejar_from_dict(cookies)
351 unmodified lines
modified:requests/sessions.py+7 added-12 removed
4 unmodified lines
5~~~~~~~~~~~~~~~~67This module provides a Session object to manage and persist settings across8requests (cookies, auth, proxies).99"""10import os11from collections import Mapping12from datetime import datetime
25 unmodified lines
38REDIRECT_CACHE_SIZE = 1000394041def merge_setting(request_setting, session_setting, dict_class=OrderedDict):43 """44 Determines appropriate setting for a given request, taking into account the45 explicit setting on that request, and the setting in the session. If a42 """Determines appropriate setting for a given request, taking into account43 the explicit setting on that request, and the setting in the session. If a44 setting is a dictionary, they will be merged together using `dict_class`45 """4647 if session_setting is None:
21 unmodified lines
69 return merged_setting707172def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):75 """76 Properly merges both requests and session hooks.73 """Properly merges both requests and session hooks.7475 This is necessary because when request_hooks == {'response': []}, the76 merge breaks Session hooks entirely.77 """
103 unmodified lines
181 i += 1182 yield resp183184 def rebuild_auth(self, prepared_request, response):188 """189 When being redirected we may want to strip authentication from the185 """When being redirected we may want to strip authentication from the186 request to avoid leaking credentials. This method intelligently removes187 and reapplies authentication where possible to avoid credential loss.188 """189 headers = prepared_request.headers
15 unmodified lines
205206 return207208 def rebuild_proxies(self, prepared_request, proxies):213 """214 This method re-evaluates the proxy configuration by considering the209 """This method re-evaluates the proxy configuration by considering the210 environment variables. If we are redirected to a URL covered by211 NO_PROXY, we strip the proxy configuration. Otherwise, we set missing212 proxy keys for this URL (in case they were stripped by a previous213 redirect).
441 unmodified lines
655656 def mount(self, prefix, adapter):657 """Registers a connection adapter to a prefix.658664 Adapters are sorted in descending order by key length."""665659 Adapters are sorted in descending order by key length.660 """661 self.adapters[prefix] = adapter662 keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]663664 for key in keys_to_move:
21 unmodified lines
modified:requests/structures.py+1 added-4 removed
3 unmodified lines
4requests.structures5~~~~~~~~~~~~~~~~~~~67Data structures that power Requests.88"""910import collections1112from .compat import OrderedDict131415class CaseInsensitiveDict(collections.MutableMapping):17 """18 A case-insensitive ``dict``-like object.16 """A case-insensitive ``dict``-like object.1718 Implements all methods and operations of19 ``collections.MutableMapping`` as well as dict's ``copy``. Also20 provides ``lower_items``.
15 unmodified lines
3637 If the constructor, ``.update``, or equality comparison38 operations are given keys that have equal ``.lower()``s, the39 behavior is undefined.4240 """4142 def __init__(self, data=None, **kwargs):43 self._store = OrderedDict()
62 unmodified lines
modified:requests/utils.py+14 added-20 removed
4 unmodified lines
5~~~~~~~~~~~~~~67This module provides utility functions that are used within Requests8that are also useful for external consumption.99"""1011import cgi12import codecs
385 unmodified lines
398 Tried:399400 1. charset from content-type401 2. fall back and replace all unicode characters403402 """403 warnings.warn((404 'In requests 3.0, get_unicode_from_response will be removed. For '405 'more information, please see the discussion on issue #2266. (This'
66 unmodified lines
472 return quote(uri, safe=safe_without_percent)473474475def address_in_network(ip, net):478 """479 This function allows you to check if on IP belongs to a network subnet476 """This function allows you to check if on IP belongs to a network subnet477478 Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24479 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24480 """481 ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
3 unmodified lines
485 return (ipaddr & netmask) == (network & netmask)486487488def dotted_netmask(mask):491 """492 Converts mask from /xx format to xxx.xxx.xxx.xxx489 """Converts mask from /xx format to xxx.xxx.xxx.xxx490491 Example: if mask is 24 function returns 255.255.255.0492 """493 bits = 0xffffffff ^ (1 << 32 - mask) - 1494 return socket.inet_ntoa(struct.pack('>I', bits))
27 unmodified lines
522 return True523524525def should_bypass_proxies(url):528 """529 Returns whether we should bypass proxies or not.530 """526 """Returns whether we should bypass proxies or not."""527 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())528529 # First check whether no_proxy is defined. If it is, check that the URL530 # we're getting isn't in the no_proxy list.
92 unmodified lines
623def parse_header_links(value):624 """Return a dict of parsed link headers proxies.625626 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"631627 """628629 links = []630
56 unmodified lines
687688689def prepend_scheme_if_needed(url, new_scheme):690 """Given a URL that may or may not have a scheme, prepend the given scheme.696 Does not replace a present scheme with the one provided as an argument."""691 Does not replace a present scheme with the one provided as an argument.692 """693 scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)694695 # urlparse is a finicky beast, and sometimes decides that there isn't a696 # netloc present. Assume that it's being over-cautious, and switch netloc
5 unmodified lines
702703704def get_auth_from_url(url):705 """Given a url with authentication components, extract them into a tuple of710 username,password."""706 username,password.707 """708 parsed = urlparse(url)709710 try:711 auth = (unquote(parsed.username), unquote(parsed.password))
3 unmodified lines
715 return auth716717718def to_native_string(string, encoding='ascii'):719 """Given a string object, regardless of type, returns a representation of720 that string in the native string type, encoding and decoding where721 necessary. This assumes ASCII unless told otherwise.722 """723 Given a string object, regardless of type, returns a representation of that724 string in the native string type, encoding and decoding where necessary.725 This assumes ASCII unless told otherwise.726 """723 if isinstance(string, builtin_str):724 out = string725 else:726 if is_py2:
8 unmodified lines
735_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')736_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')737738def check_header_validity(header):743 """Verifies that header value is a string which doesn't contain 739 """Verifies that header value is a string which doesn't contain740 leading whitespace or return characters. This prevents unintended741 header injection.742743 :param header: tuple, in the format (name, value).
12 unmodified lines
756 "not %s" % (value, type(value)))757758759def urldefragauth(url):764 """765 Given a url remove the fragment and the authentication part766 """760 """Given a url remove the fragment and the authentication part"""761 scheme, netloc, path, params, query, fragment = urlparse(url)762763 # see func:`prepend_scheme_if_needed`764 if not netloc:
5 unmodified lines
modified:tests/testserver/server.py+2 added
1# -*- coding: utf-8 -*-23import threading4import socket5import select6
121 unmodified lines
modified:tests/__init__.py+1 added-1 removed
1# coding: utf-81# -*- coding: utf-8 -*-23"""Requests test package initialisation."""45import warnings
17 unmodified lines
modified:tests/compat.py+2 added-1 removed
1# coding: utf-81# -*- coding: utf-8 -*-23from requests.compat import is_py3456try:
15 unmodified lines
modified:tests/conftest.py+2 added-1 removed
1# coding: utf-81# -*- coding: utf-8 -*-23import pytest4from requests.compat import urljoin56
18 unmodified lines
modified:tests/test_hooks.py+2 added-1 removed
1# coding: utf-81# -*- coding: utf-8 -*-23import pytest45from requests import hooks6
17 unmodified lines
modified:tests/test_lowlevel.py+2 added
1# -*- coding: utf-8 -*-23import os4import pytest5import threading6import requests
52 unmodified lines
modified:tests/test_requests.py+3 added-6 removed
953 unmodified lines
954 assert next(iter(r))955 io.close()956957 def test_response_decode_unicode(self):958 """959 When called with decode_unicode, Response.iter_content should always958 """When called with decode_unicode, Response.iter_content should always959 return unicode.960 """961 r = requests.Response()962 r._content_consumed = True
82 unmodified lines
1045 r = s.send(r.prepare())1046 assert r.status_code == 20010471048 def test_fixes_1329(self, httpbin):1050 """1051 Ensure that header updates are done case-insensitively.1052 """1049 """Ensure that header updates are done case-insensitively."""1050 s = requests.Session()1051 s.headers.update({'ACCEPT': 'BOGUS'})1052 s.headers.update({'accept': 'application/json'})1053 r = s.get(httpbin('get'))
520 unmodified lines
1574 requests.get(httpbin('get'), timeout=timeout)1575 assert error_text in str(e)15761577 def test_none_timeout(self, httpbin):1581 """ Check that you can set None as a valid timeout value.1578 """Check that you can set None as a valid timeout value.15791580 To actually test this behavior, we'd want to check that setting the1581 timeout to None actually lets the request block past the system default1582 timeout. However, this would make the test suite unbearably slow.
200 unmodified lines
modified:tests/test_structures.py+4 added-7 removed
1# coding: utf-81# -*- coding: utf-8 -*-23import pytest45from requests.structures import CaseInsensitiveDict, LookupDict6
1 unmodified line
8class TestCaseInsensitiveDict:910 @pytest.fixture(autouse=True)11 def setup(self):11 """12 CaseInsensitiveDict instance with "Accept" header.13 """12 """CaseInsensitiveDict instance with "Accept" header."""13 self.case_insensitive_dict = CaseInsensitiveDict()14 self.case_insensitive_dict['Accept'] = 'application/json'1516 def test_list(self):
35 unmodified lines
52class TestLookupDict:5354 @pytest.fixture(autouse=True)55 def setup(self):57 """58 LookupDict instance with "bad_gateway" attribute.59 """56 """LookupDict instance with "bad_gateway" attribute."""57 self.lookup_dict = LookupDict('test')58 self.lookup_dict.bad_gateway = 5025960 def test_repr(self):
16 unmodified lines
modified:tests/test_testserver.py+2 added
1# -*- coding: utf-8 -*-23import threading4import socket5import time6
158 unmodified lines
modified:tests/test_utils.py+8 added-9 removed
1# coding: utf-81# -*- coding: utf-8 -*-23from io import BytesIO45import pytest6from requests import compat
33 unmodified lines
40 assert super_len(s) == 04142 @pytest.mark.parametrize('error', [IOError, OSError])43 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):43 """44 If tell() raises errors, assume the cursor is at position zero.45 """44 """If tell() raises errors, assume the cursor is at position zero."""45 class BoomFile(object):46 def __len__(self):47 return 548
53 unmodified lines
102103104class TestGetEnvironProxies:105 """Ensures that IP addresses are correctly matches with ranges107 in no_proxy variable."""106 in no_proxy variable.107 """108109 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])110 def no_proxy(self, request, monkeypatch):111 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')
175 unmodified lines
287 'http://example.com/fiz?buz=%25ppicture',288 ),289 ))290def test_requote_uri_with_unquoted_percents(uri, expected):291 """See: https://github.com/kennethreitz/requests/issues/2356292 """291 """See: https://github.com/kennethreitz/requests/issues/2356"""292 assert requote_uri(uri) == expected293294295@pytest.mark.parametrize(
162 unmodified lines
458 ('http://172.16.1.12:5000/', False),459 ('http://google.com:5000/v1.0/', False),460 ))461def test_should_bypass_proxies(url, expected, monkeypatch):462 """Tests for function should_bypass_proxies to check if proxy463 can be bypassed or not464 """464 Tests for function should_bypass_proxies to check if proxy can be bypassed or not465 """465 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')466 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')467 assert should_bypass_proxies(url) == expected
modified:tests/utils.py+2 added
1# -*- coding: utf-8 -*-23import contextlib4import os56
13 unmodified lines