Merge pull request #3484 from scop/rtypes
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Document bunch of return types
authored by Cory Benfield · committed by GitHub · parents 9313978, 542fbbc · Browse files · 5 files·+113 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+113 added−11 removed
- other:+113 added−11 removed
Provenance
- Commit
5259b37- Tree
d61e6cf- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9313978- Parent 2
542fbbc
5 files changed+113 added−11 removed
modified:requests/adapters.py+6 added
166 unmodified lines167 168 :param proxy: The proxy to return a urllib3 ProxyManager for.169 :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.170 :returns: ProxyManager171+ :rtype: requests.packages.urllib3.ProxyManager172 """173 if proxy in self.proxy_manager:174 manager = self.proxy_manager[proxy]175 elif proxy.lower().startswith('socks'):68 unmodified lines244 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`245 246 :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.247 :param resp: The urllib3 response object.248+ :rtype: requests.Response249 """250 response = Response()251 252 # Fallback to None if there's no status_code, for whatever reason.27 unmodified lines280 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.281 282 :param url: The URL to connect to.283 :param proxies: (optional) A Requests-style dictionary of proxies used on this request.284+ :rtype: requests.packages.urllib3.ConnectionPool285 """286 proxy = select_proxy(url, proxies)287 288 if proxy:29 unmodified lines318 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.319 320 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.321 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.322+ :rtype: str323 """324 proxy = select_proxy(request.url, proxies)325 scheme = urlparse(request.url).scheme326 33 unmodified lines360 when subclassing the361 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.362 363 :param proxies: The url of the proxy being used for this request.364+ :rtype: dict365 """366 headers = {}367 username, password = get_auth_from_url(proxy)368 14 unmodified lines383 :type timeout: float or tuple384 :param verify: (optional) Whether to verify SSL certificates.385 :param cert: (optional) Any user-provided SSL certificate to be trusted.386 :param proxies: (optional) The proxies dictionary to apply to the request.387+ :rtype: requests.Response388 """389 390 conn = self.get_connection(request.url, proxies)391 112 unmodified linesmodified:requests/auth.py+8 added-1 removed
88 unmodified lines89 self._thread_local.pos = None90 self._thread_local.num_401_calls = None91 92 def build_digest_header(self, method, url):93+ """94+ :rtype: str95+ """96 97 realm = self._thread_local.chal['realm']98 nonce = self._thread_local.chal['nonce']99 qop = self._thread_local.chal.get('qop')84 unmodified lines184 if r.is_redirect:185 self._thread_local.num_401_calls = 1186 187 def handle_401(self, r, **kwargs):185- """Takes the given response and tries digest-auth, if needed."""188+ """189+ Takes the given response and tries digest-auth, if needed.190 191+ :rtype: requests.Response192+ """193+194 if self._thread_local.pos is not None:195 # Rewind the file position indicator of the body to where196 # it was to resend the request.197 r.request.body.seek(self._thread_local.pos)55 unmodified linesmodified:requests/cookies.py+9 added-1 removed
132 unmodified lines133 jar.extract_cookies(res, req)134 135 136 def get_cookie_header(jar, request):137- """Produce an appropriate Cookie header string to be sent with `request`, or None."""137+ """138+ Produce an appropriate Cookie header string to be sent with `request`, or None.139+140+ :rtype: str141+ """142 r = MockRequest(request)143 jar.add_cookie_header(r)144 return r.get_new_headers().get('Cookie')145 140 unmodified lines286 287 def multiple_domains(self):288 """Returns True if there are multiple domains in the jar.289 Returns False otherwise.290+291+ :rtype: bool292 """293 domains = []294 for cookie in iter(self):295 if cookie.domain is not None and cookie.domain in domains:4 unmodified lines300 def get_dict(self, domain=None, path=None):301 """Takes as an argument an optional domain and path and returns a plain302 old Python dict of name-value pairs of cookies that meet the303 requirements.304+305+ :rtype: dict306 """307 dictionary = {}308 for cookie in iter(self):309 if (domain is None or cookie.domain == domain) and (path is None231 unmodified linesmodified:requests/sessions.py+30 added-4 removed
212 unmodified lines213 redirect).214 215 This method also replaces the Proxy-Authorization header where216 necessary.217+218+ :rtype: dict219 """220 headers = prepared_request.headers221 url = prepared_request.url222 scheme = urlparse(url).scheme138 unmodified lines361 :class:`Session`.362 363 :param request: :class:`Request` instance to prepare with this364 session's settings.365+ :rtype: requests.PreparedRequest366 """367 cookies = request.cookies or {}368 369 # Bootstrap CookieJar.109 unmodified lines479 """Sends a GET request. Returns :class:`Response` object.480 481 :param url: URL for the new :class:`Request` object.482 :param \*\*kwargs: Optional arguments that ``request`` takes.483+ :rtype: requests.Response484 """485 486 kwargs.setdefault('allow_redirects', True)487 return self.request('GET', url, **kwargs)2 unmodified lines490 """Sends a OPTIONS request. Returns :class:`Response` object.491 492 :param url: URL for the new :class:`Request` object.493 :param \*\*kwargs: Optional arguments that ``request`` takes.494+ :rtype: requests.Response495 """496 497 kwargs.setdefault('allow_redirects', True)498 return self.request('OPTIONS', url, **kwargs)2 unmodified lines501 """Sends a HEAD request. Returns :class:`Response` object.502 503 :param url: URL for the new :class:`Request` object.504 :param \*\*kwargs: Optional arguments that ``request`` takes.505+ :rtype: requests.Response506 """507 508 kwargs.setdefault('allow_redirects', False)509 return self.request('HEAD', url, **kwargs)4 unmodified lines514 :param url: URL for the new :class:`Request` object.515 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.516 :param json: (optional) json to send in the body of the :class:`Request`.517 :param \*\*kwargs: Optional arguments that ``request`` takes.518+ :rtype: requests.Response519 """520 521 return self.request('POST', url, data=data, json=json, **kwargs)522 2 unmodified lines525 526 :param url: URL for the new :class:`Request` object.527 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.528 :param \*\*kwargs: Optional arguments that ``request`` takes.529+ :rtype: requests.Response530 """531 532 return self.request('PUT', url, data=data, **kwargs)533 2 unmodified lines536 537 :param url: URL for the new :class:`Request` object.538 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.539 :param \*\*kwargs: Optional arguments that ``request`` takes.540+ :rtype: requests.Response541 """542 543 return self.request('PATCH', url, data=data, **kwargs)544 1 unmodified line546 """Sends a DELETE request. Returns :class:`Response` object.547 548 :param url: URL for the new :class:`Request` object.549 :param \*\*kwargs: Optional arguments that ``request`` takes.550+ :rtype: requests.Response551 """552 553 return self.request('DELETE', url, **kwargs)554 555 def send(self, request, **kwargs):546- """Send a given PreparedRequest."""556+ """557+ Send a given PreparedRequest.558+559+ :rtype: requests.Response560+ """561 # Set defaults that the hooks can utilize to ensure they always have562 # the correct parameters to reproduce the previous request.563 kwargs.setdefault('stream', self.stream)564 kwargs.setdefault('verify', self.verify)63 unmodified lines628 629 return r630 631 def merge_environment_settings(self, url, proxies, stream, verify, cert):618- """Check the environment and merge it with some settings."""632+ """633+ Check the environment and merge it with some settings.634+635+ :rtype: dict636+ """637 # Gather clues from the surrounding environment.638 if self.trust_env:639 # Set environment's proxies.640 env_proxies = get_environ_proxies(url) or {}15 unmodified lines656 return {'verify': verify, 'proxies': proxies, 'stream': stream,657 'cert': cert}658 659 def get_adapter(self, url):642- """Returns the appropriate connection adapter for the given URL."""660+ """661+ Returns the appropriate connection adapter for the given URL.662+663+ :rtype: requests.adapters.BaseAdapter664+ """665 for (prefix, adapter) in self.adapters.items():666 667 if url.lower().startswith(prefix):668 return adapter32 unmodified lines701 self.redirect_cache[redirect] = to702 703 704 def session():683- """Returns a :class:`Session` for context-management."""705+ """706+ Returns a :class:`Session` for context-management.707 708+ :rtype: Session709+ """710+711 return Session()modified:requests/utils.py+60 added-5 removed
162 unmodified lines163 >>> from_key_val_list('string')164 ValueError: need more than 1 value to unpack165 >>> from_key_val_list({'key': 'val'})166 OrderedDict([('key', 'val')])167+168+ :rtype: OrderedDict169 """170 if value is None:171 return None172 14 unmodified lines187 >>> to_key_val_list({'key': 'val'})188 [('key', 'val')]189 >>> to_key_val_list('string')190 ValueError: cannot encode objects that are not 2-tuples.191+192+ :rtype: list193 """194 if value is None:195 return None196 27 unmodified lines224 :func:`dump_header` function.225 226 :param value: a string with a list header.227 :return: :class:`list`228+ :rtype: list229 """230 result = []231 for item in _parse_list_header(value):232 if item[:1] == item[-1:] == '"':22 unmodified lines255 :func:`dump_header` function.256 257 :param value: a string with a dict header.258 :return: :class:`dict`259+ :rtype: dict260 """261 result = {}262 for item in _parse_list_header(value):263 if '=' not in item:12 unmodified lines276 This does not use the real unquoting but what browsers are actually277 using for quoting.278 279 :param value: the header value to unquote.280+ :rtype: str281 """282 if value and value[0] == value[-1] == '"':283 # this is not the real unquoting, but fixing this so that the284 # RFC is met will result in bugs with internet explorer and14 unmodified lines299 def dict_from_cookiejar(cj):300 """Returns a key/value dictionary from a CookieJar.301 302 :param cj: CookieJar object to extract cookies from.303+ :rtype: dict304 """305 306 cookie_dict = {}307 7 unmodified lines315 """Returns a CookieJar from a key/value dictionary.316 317 :param cj: CookieJar to insert cookies into.318 :param cookie_dict: Dict of key/values to insert into CookieJar.319+ :rtype: CookieJar320 """321 322 cj2 = cookiejar_from_dict(cookie_dict)323 cj.update(cj2)23 unmodified lines347 def get_encoding_from_headers(headers):348 """Returns encodings from given HTTP Header Dict.349 350 :param headers: dictionary to extract encoding from.351+ :rtype: str352 """353 354 content_type = headers.get('content-type')355 52 unmodified lines408 Tried:409 410 1. charset from content-type411 2. fall back and replace all unicode characters412+413+ :rtype: str414 """415 warnings.warn((416 'In requests 3.0, get_unicode_from_response will be removed. For '417 'more information, please see the discussion on issue #2266. (This'26 unmodified lines444 445 def unquote_unreserved(uri):446 """Un-escape any percent-escape sequences in a URI that are unreserved447 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.448+449+ :rtype: str450 """451 parts = uri.split('%')452 for i in range(1, len(parts)):453 h = parts[i][0:2]16 unmodified lines470 """Re-quote the given URI.471 472 This function passes the given URI through an unquote/quote cycle to473 ensure that it is fully and consistently quoted.474+475+ :rtype: str476 """477 safe_with_percent = "!#$%&'()*+,/:;=?@[]~"478 safe_without_percent = "!#$&'()*+,/:;=?@[]~"479 try:12 unmodified lines492 """This function allows you to check if on IP belongs to a network subnet493 494 Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24495 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24496+497+ :rtype: bool498 """499 ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]500 netaddr, bits = net.split('/')501 netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]4 unmodified lines506 def dotted_netmask(mask):507 """Converts mask from /xx format to xxx.xxx.xxx.xxx508 509 Example: if mask is 24 function returns 255.255.255.0510+511+ :rtype: str512 """513 bits = 0xffffffff ^ (1 << 32 - mask) - 1514 return socket.inet_ntoa(struct.pack('>I', bits))515 516 517 def is_ipv4_address(string_ip):518+ """519+ :rtype: bool520+ """521 try:522 socket.inet_aton(string_ip)523 except socket.error:524 return False525 return True526 527 528 def is_valid_cidr(string_network):506- """Very simple check of the cidr format in no_proxy variable"""529+ """530+ Very simple check of the cidr format in no_proxy variable.531+532+ :rtype: bool533+ """534 if string_network.count('/') == 1:535 try:536 mask = int(string_network.split('/')[1])537 except ValueError:11 unmodified lines549 return True550 551 552 def should_bypass_proxies(url):526- """Returns whether we should bypass proxies or not."""553+ """554+ Returns whether we should bypass proxies or not.555+556+ :rtype: bool557+ """558 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())559 560 # First check whether no_proxy is defined. If it is, check that the URL561 # we're getting isn't in the no_proxy list.41 unmodified lines603 return False604 605 606 def get_environ_proxies(url):576- """Return a dict of environment proxies."""607+ """608+ Return a dict of environment proxies.609+610+ :rtype: dict611+ """612 if should_bypass_proxies(url):613 return {}614 else:615 return getproxies()25 unmodified lines641 return proxy642 643 644 def default_user_agent(name="python-requests"):610- """Return a string representing the default user agent."""645+ """646+ Return a string representing the default user agent.647+648+ :rtype: str649+ """650 return '%s/%s' % (name, __version__)651 652 653 def default_headers():654+ """655+ :rtype: requests.structures.CaseInsensitiveDict656+ """657 return CaseInsensitiveDict({658 'User-Agent': default_user_agent(),659 'Accept-Encoding': ', '.join(('gzip', 'deflate')),660 'Accept': '*/*',4 unmodified lines665 def parse_header_links(value):666 """Return a dict of parsed link headers proxies.667 668 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"669+670+ :rtype: list671 """672 673 links = []674 26 unmodified lines701 _null3 = _null * 3702 703 704 def guess_json_utf(data):705+ """706+ :rtype: str707+ """708 # JSON always starts with two ASCII characters, so detection is as709 # easy as counting the nulls and from their location and count710 # determine the encoding. Also detect a BOM, if present.711 sample = data[:4]23 unmodified lines735 736 def prepend_scheme_if_needed(url, new_scheme):737 """Given a URL that may or may not have a scheme, prepend the given scheme.738 Does not replace a present scheme with the one provided as an argument.739+740+ :rtype: str741 """742 scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)743 744 # urlparse is a finicky beast, and sometimes decides that there isn't a7 unmodified lines752 753 def get_auth_from_url(url):754 """Given a url with authentication components, extract them into a tuple of755 username,password.756+757+ :rtype: (str,str)758 """759 parsed = urlparse(url)760 761 try:45 unmodified lines807 "not %s" % (value, type(value)))808 809 810 def urldefragauth(url):760- """Given a url remove the fragment and the authentication part"""811+ """812+ Given a url remove the fragment and the authentication part.813+814+ :rtype: str815+ """816 scheme, netloc, path, params, query, fragment = urlparse(url)817 818 # see func:`prepend_scheme_if_needed`819 if not netloc:5 unmodified lines