Skip to content
Myr

making class and function docstrings consistent

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

authored by Nate Prewitt · committed by Nate Prewitt · parent 15a3869 · Browse files · 9 files+101 added−92 removed
This commit

State

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

Diff stats

9 files+101 added−92 removed

  • tests:+11 added−20 removed
  • other:+90 added−72 removed

9 files+101 added−92 removed

modified:requests/cookies.py+62 added-27 removed
159 unmodified lines
160161162class CookieConflictError(RuntimeError):163 """There are two cookies that meet the criteria specified in the cookie jar.164 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
16 unmodified lines
186 """Dict-like get() that also supports optional domain and path args in187 order to resolve naming collisions from using one cookie jar over188 multiple domains.189189 .. warning:: operation is O(n), not O(1)."""190 .. warning:: operation is O(n), not O(1).191 """192 try:193 return self._find_no_duplicates(name, domain, path)194 except KeyError:195 return default196197 def set(self, name, value, **kwargs):198 """Dict-like set() that also supports optional domain and path args in199 order to resolve naming collisions from using one cookie jar over198 multiple domains."""200 multiple domains.201 """202 # support client code that unsets cookies by assignment of a None value:203 if value is None:204 remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))205 return
6 unmodified lines
212 return c213214 def iterkeys(self):215 """Dict-like iterkeys() that returns an iterator of names of cookies213 from the jar. See itervalues() and iteritems()."""216 from the jar.217218 .. seealso:: itervalues() and iteritems().219 """220 for cookie in iter(self):221 yield cookie.name222223 def keys(self):224 """Dict-like keys() that returns a list of names of cookies from the219 jar. See values() and items()."""225 jar.226227 .. seealso:: values() and items().228 """229 return list(self.iterkeys())230231 def itervalues(self):232 """Dict-like itervalues() that returns an iterator of values of cookies224 from the jar. See iterkeys() and iteritems()."""233 from the jar.234235 .. seealso:: iterkeys() and iteritems().236 """237 for cookie in iter(self):238 yield cookie.value239240 def values(self):241 """Dict-like values() that returns a list of values of cookies from the230 jar. See keys() and items()."""242 jar.243244 .. seealso:: keys() and items().245 """246 return list(self.itervalues())247248 def iteritems(self):249 """Dict-like iteritems() that returns an iterator of name-value tuples235 from the jar. See iterkeys() and itervalues()."""250 from the jar.251252 .. seealso:: iterkeys() and itervalues().253 """254 for cookie in iter(self):255 yield cookie.name, cookie.value256257 def items(self):258 """Dict-like items() that returns a list of name-value tuples from the241 jar. See keys() and values(). Allows client-code to call242 ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value243 pairs."""259 jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a260 vanilla python dict of key value pairs.261262 .. seealso:: keys() and values().263 """264 return list(self.iteritems())265266 def list_domains(self):267 """Utility method to list all the domains in the jar."""
12 unmodified lines
280 return paths281282 def multiple_domains(self):283 """Returns True if there are multiple domains in the jar.264 Returns False otherwise."""284 Returns False otherwise.285 """286 domains = []287 for cookie in iter(self):288 if cookie.domain is not None and cookie.domain in domains:289 return True
2 unmodified lines
292293 def get_dict(self, domain=None, path=None):294 """Takes as an argument an optional domain and path and returns a plain295 old Python dict of name-value pairs of cookies that meet the275 requirements."""296 requirements.297 """298 dictionary = {}299 for cookie in iter(self):300 if (domain is None or cookie.domain == domain) and (path is None301 or cookie.path == path):
10 unmodified lines
312 """Dict-like __getitem__() for compatibility with client code. Throws313 exception if there are more than one cookie with name. In that case,314 use the more explicit get() method instead.315294 .. warning:: operation is O(n), not O(1)."""295316 .. warning:: operation is O(n), not O(1).317 """318 return self._find_no_duplicates(name)319320 def __setitem__(self, name, value):321 """Dict-like __setitem__ for compatibility with client code. Throws322 exception if there is already a cookie of that name in the jar. In that301 case, use the more explicit set() method instead."""302323 case, use the more explicit set() method instead.324 """325 self.set(name, value)326327 def __delitem__(self, name):328 """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s307 ``remove_cookie_by_name()``."""329 ``remove_cookie_by_name()``.330 """331 remove_cookie_by_name(self, name)332333 def set_cookie(self, cookie, *args, **kwargs):334 if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
8 unmodified lines
343 else:344 super(RequestsCookieJar, self).update(other)345346 def _find(self, name, domain=None, path=None):324 """Requests uses this method internally to get cookie values. Takes as325 args name and optional domain and path. Returns a cookie.value. If326 there are conflicting cookies, _find arbitrarily chooses one. See327 _find_no_duplicates if you want an exception thrown if there are328 conflicting cookies."""347 """Requests uses this method internally to get cookie values.348349 If there are conflicting cookies, _find arbitrarily chooses one.350 See _find_no_duplicates if you want an exception thrown if there are351 conflicting cookies.352353 :param name: a string containing name of cookie354 :param domain: (optional) string containing domain of cookie355 :param path: (optional) string containing path of cookie356 :return: cookie.value357 """358 for cookie in iter(self):359 if cookie.name == name:360 if domain is None or cookie.domain == domain:361 if path is None or cookie.path == path:
2 unmodified lines
364 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))365366 def _find_no_duplicates(self, name, domain=None, path=None):367 """Both ``__get_item__`` and ``get`` call this function: it's never339 used elsewhere in Requests. Takes as args name and optional domain and340 path. Returns a cookie.value. Throws KeyError if cookie is not found341 and CookieConflictError if there are multiple cookies that match name342 and optionally domain and path."""368 used elsewhere in Requests.369370 :param name: a string containing name of cookie371 :param domain: (optional) string containing domain of cookie372 :param path: (optional) string containing path of cookie373 :raises KeyError: if cookie is not found374 :raises CookieConflictError: if there are multiple cookies375 that match name and optionally domain and path376 :return: cookie.value377 """378 toReturn = None379 for cookie in iter(self):380 if cookie.name == name:381 if domain is None or cookie.domain == domain:
150 unmodified lines
modified:requests/exceptions.py+4 added-7 removed
9 unmodified lines
101112class RequestException(IOError):13 """There was an ambiguous exception that occurred while handling your14 request."""14 request.15 """1617 def __init__(self, *args, **kwargs):17 """18 Initialize RequestException with `request` and `response` objects.19 """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):114 """115 A file was opened in text mode, but Requests determined its binary length.116 """113 """A file was opened in text mode, but Requests determined its binary length."""114 pass
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 """210 def __init__(self, method=None, url=None, headers=None, files=None,211 data=None, params=None, auth=None, cookies=None, hooks=None, json=None):212
54 unmodified lines
267268 >>> s = requests.Session()269 >>> s.send(r)270 <Response [200]>273271 """272273 def __init__(self):274 #: HTTP verb to send to the server.
237 unmodified lines
512 will not be regenerated if it already exists, meaning this function513 can only be called once for the life of the514 :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls515 to ``prepare_cookies`` will have no actual effect, unless the "Cookie"519 header is removed beforehand."""520516 header is removed beforehand.517 """518 if isinstance(cookies, cookielib.CookieJar):519 self._cookies = cookies520 else:521 self._cookies = cookiejar_from_dict(cookies)
351 unmodified lines
modified:requests/sessions.py+7 added-11 removed
37 unmodified lines
38REDIRECT_CACHE_SIZE = 1000394041def merge_setting(request_setting, session_setting, dict_class=OrderedDict):42 """43 Determines appropriate setting for a given request, taking into account the44 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):74 """75 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):187 """188 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):212 """213 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).
442 unmodified lines
656657 def mount(self, prefix, adapter):658 """Registers a connection adapter to a prefix.659664 Adapters are sorted in descending order by key length."""665660 Adapters are sorted in descending order by key length.661 """662 self.adapters[prefix] = adapter663 keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]664665 for key in keys_to_move:
21 unmodified lines
modified:requests/structures.py+1 added-3 removed
11 unmodified lines
12from .compat import OrderedDict131415class CaseInsensitiveDict(collections.MutableMapping):16 """17 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.4140 """41 def __init__(self, data=None, **kwargs):42 self._store = OrderedDict()43 if data is None:
60 unmodified lines
modified:requests/utils.py+14 added-19 removed
397 unmodified lines
398 Tried:399400 1. charset from content-type401 2. fall back and replace all unicode characters402402 """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):477 """478 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):490 """491 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):527 """528 Returns whether we should bypass proxies or not.529 """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"630627 """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.695 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 of709 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 """722 Given a string object, regardless of type, returns a representation of that723 string in the native string type, encoding and decoding where necessary.724 This assumes ASCII unless told otherwise.725 """723 if isinstance(string, builtin_str):724 out = string725 else:726 if is_py2:
7 unmodified lines
734_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')735_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')736737def check_header_validity(header):741 """Verifies that header value is a string which doesn't contain 738 """Verifies that header value is a string which doesn't contain739 leading whitespace or return characters. This prevents unintended740 header injection.741742 :param header: tuple, in the format (name, value).
11 unmodified lines
754 raise InvalidHeader("Header value %s must be of type str or bytes, " 755 "not %s" % (value, type(value)))756757def urldefragauth(url):761 """762 Given a url remove the fragment and the authentication part763 """758 """Given a url remove the fragment and the authentication part"""759 scheme, netloc, path, params, query, fragment = urlparse(url)760761 # see func:`prepend_scheme_if_needed`762 if not netloc:
5 unmodified lines
modified:tests/test_requests.py+3 added-6 removed
955 unmodified lines
956 assert next(iter(r))957 io.close()958959 def test_response_decode_unicode(self):960 """961 When called with decode_unicode, Response.iter_content should always960 """When called with decode_unicode, Response.iter_content should always961 return unicode.962 """963 r = requests.Response()964 r._content_consumed = True
82 unmodified lines
1047 r = s.send(r.prepare())1048 assert r.status_code == 20010491050 def test_fixes_1329(self, httpbin):1052 """1053 Ensure that header updates are done case-insensitively.1054 """1051 """Ensure that header updates are done case-insensitively."""1052 s = requests.Session()1053 s.headers.update({'ACCEPT': 'BOGUS'})1054 s.headers.update({'accept': 'application/json'})1055 r = s.get(httpbin('get'))
520 unmodified lines
1576 requests.get(httpbin('get'), timeout=timeout)1577 assert error_text in str(e)15781579 def test_none_timeout(self, httpbin):1583 """ Check that you can set None as a valid timeout value.1580 """Check that you can set None as a valid timeout value.15811582 To actually test this behavior, we'd want to check that setting the1583 timeout to None actually lets the request block past the system default1584 timeout. However, this would make the test suite unbearably slow.
200 unmodified lines
modified:tests/test_structures.py+2 added-6 removed
7 unmodified lines
8class TestCaseInsensitiveDict:910 @pytest.fixture(autouse=True)11 def setup(self):12 """13 CaseInsensitiveDict instance with "Accept" header.14 """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):58 """59 LookupDict instance with "bad_gateway" attribute.60 """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_utils.py+6 added-8 removed
39 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):44 """45 If tell() raises errors, assume the cursor is at position zero.46 """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 ranges108 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):292 """See: https://github.com/kennethreitz/requests/issues/2356293 """291 """See: https://github.com/kennethreitz/requests/issues/2356"""292 assert requote_uri(uri) == expected293294295@pytest.mark.parametrize(
161 unmodified lines
457 ('http://172.16.1.12:5000/', False),458 ('http://google.com:5000/v1.0/', False),459 ))460def test_should_bypass_proxies(url, expected, monkeypatch):461 """Tests for function should_bypass_proxies to check if proxy462 can be bypassed or not463 """464 Tests for function should_bypass_proxies to check if proxy can be bypassed or not465 """464 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')465 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')466 assert should_bypass_proxies(url) == expected