Skip to content
Myr

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

5 files+113 added−11 removed

modified:requests/adapters.py+6 added
166 unmodified lines
167168 :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 lines
244 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`245246 :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()251252 # Fallback to None if there's no status_code, for whatever reason.
27 unmodified lines
280 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.281282 :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)287288 if proxy:
29 unmodified lines
318 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.319320 :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 lines
360 when subclassing the361 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.362363 :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 lines
383 :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 """389390 conn = self.get_connection(request.url, proxies)391
112 unmodified lines
modified:requests/auth.py+8 added-1 removed
88 unmodified lines
89 self._thread_local.pos = None90 self._thread_local.num_401_calls = None9192 def build_digest_header(self, method, url):93 """94 :rtype: str95 """9697 realm = self._thread_local.chal['realm']98 nonce = self._thread_local.chal['nonce']99 qop = self._thread_local.chal.get('qop')
84 unmodified lines
184 if r.is_redirect:185 self._thread_local.num_401_calls = 1186187 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.190191 :rtype: requests.Response192 """193194 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 lines
modified:requests/cookies.py+9 added-1 removed
132 unmodified lines
133 jar.extract_cookies(res, req)134135136def 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.139140 :rtype: str141 """142 r = MockRequest(request)143 jar.add_cookie_header(r)144 return r.get_new_headers().get('Cookie')145
140 unmodified lines
286287 def multiple_domains(self):288 """Returns True if there are multiple domains in the jar.289 Returns False otherwise.290291 :rtype: bool292 """293 domains = []294 for cookie in iter(self):295 if cookie.domain is not None and cookie.domain in domains:
4 unmodified lines
300 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.304305 :rtype: dict306 """307 dictionary = {}308 for cookie in iter(self):309 if (domain is None or cookie.domain == domain) and (path is None
231 unmodified lines
modified:requests/sessions.py+30 added-4 removed
212 unmodified lines
213 redirect).214215 This method also replaces the Proxy-Authorization header where216 necessary.217218 :rtype: dict219 """220 headers = prepared_request.headers221 url = prepared_request.url222 scheme = urlparse(url).scheme
138 unmodified lines
361 :class:`Session`.362363 :param request: :class:`Request` instance to prepare with this364 session's settings.365 :rtype: requests.PreparedRequest366 """367 cookies = request.cookies or {}368369 # Bootstrap CookieJar.
109 unmodified lines
479 """Sends a GET request. Returns :class:`Response` object.480481 :param url: URL for the new :class:`Request` object.482 :param \*\*kwargs: Optional arguments that ``request`` takes.483 :rtype: requests.Response484 """485486 kwargs.setdefault('allow_redirects', True)487 return self.request('GET', url, **kwargs)
2 unmodified lines
490 """Sends a OPTIONS request. Returns :class:`Response` object.491492 :param url: URL for the new :class:`Request` object.493 :param \*\*kwargs: Optional arguments that ``request`` takes.494 :rtype: requests.Response495 """496497 kwargs.setdefault('allow_redirects', True)498 return self.request('OPTIONS', url, **kwargs)
2 unmodified lines
501 """Sends a HEAD request. Returns :class:`Response` object.502503 :param url: URL for the new :class:`Request` object.504 :param \*\*kwargs: Optional arguments that ``request`` takes.505 :rtype: requests.Response506 """507508 kwargs.setdefault('allow_redirects', False)509 return self.request('HEAD', url, **kwargs)
4 unmodified lines
514 :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 """520521 return self.request('POST', url, data=data, json=json, **kwargs)522
2 unmodified lines
525526 :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 """531532 return self.request('PUT', url, data=data, **kwargs)533
2 unmodified lines
536537 :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 """542543 return self.request('PATCH', url, data=data, **kwargs)544
1 unmodified line
546 """Sends a DELETE request. Returns :class:`Response` object.547548 :param url: URL for the new :class:`Request` object.549 :param \*\*kwargs: Optional arguments that ``request`` takes.550 :rtype: requests.Response551 """552553 return self.request('DELETE', url, **kwargs)554555 def send(self, request, **kwargs):546 """Send a given PreparedRequest."""556 """557 Send a given PreparedRequest.558559 :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 lines
628629 return r630631 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.634635 :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 lines
656 return {'verify': verify, 'proxies': proxies, 'stream': stream,657 'cert': cert}658659 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.662663 :rtype: requests.adapters.BaseAdapter664 """665 for (prefix, adapter) in self.adapters.items():666667 if url.lower().startswith(prefix):668 return adapter
32 unmodified lines
701 self.redirect_cache[redirect] = to702703704def session():683 """Returns a :class:`Session` for context-management."""705 """706 Returns a :class:`Session` for context-management.707708 :rtype: Session709 """710711 return Session()
modified:requests/utils.py+60 added-5 removed
162 unmodified lines
163 >>> from_key_val_list('string')164 ValueError: need more than 1 value to unpack165 >>> from_key_val_list({'key': 'val'})166 OrderedDict([('key', 'val')])167168 :rtype: OrderedDict169 """170 if value is None:171 return None172
14 unmodified lines
187 >>> 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.191192 :rtype: list193 """194 if value is None:195 return None196
27 unmodified lines
224 :func:`dump_header` function.225226 :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 lines
255 :func:`dump_header` function.256257 :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 lines
276 This does not use the real unquoting but what browsers are actually277 using for quoting.278279 :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 and
14 unmodified lines
299def dict_from_cookiejar(cj):300 """Returns a key/value dictionary from a CookieJar.301302 :param cj: CookieJar object to extract cookies from.303 :rtype: dict304 """305306 cookie_dict = {}307
7 unmodified lines
315 """Returns a CookieJar from a key/value dictionary.316317 :param cj: CookieJar to insert cookies into.318 :param cookie_dict: Dict of key/values to insert into CookieJar.319 :rtype: CookieJar320 """321322 cj2 = cookiejar_from_dict(cookie_dict)323 cj.update(cj2)
23 unmodified lines
347def get_encoding_from_headers(headers):348 """Returns encodings from given HTTP Header Dict.349350 :param headers: dictionary to extract encoding from.351 :rtype: str352 """353354 content_type = headers.get('content-type')355
52 unmodified lines
408 Tried:409410 1. charset from content-type411 2. fall back and replace all unicode characters412413 :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 lines
444445def 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.448449 :rtype: str450 """451 parts = uri.split('%')452 for i in range(1, len(parts)):453 h = parts[i][0:2]
16 unmodified lines
470 """Re-quote the given URI.471472 This function passes the given URI through an unquote/quote cycle to473 ensure that it is fully and consistently quoted.474475 :rtype: str476 """477 safe_with_percent = "!#$%&'()*+,/:;=?@[]~"478 safe_without_percent = "!#$&'()*+,/:;=?@[]~"479 try:
12 unmodified lines
492 """This function allows you to check if on IP belongs to a network subnet493494 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/24496497 :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 lines
506def dotted_netmask(mask):507 """Converts mask from /xx format to xxx.xxx.xxx.xxx508509 Example: if mask is 24 function returns 255.255.255.0510511 :rtype: str512 """513 bits = 0xffffffff ^ (1 << 32 - mask) - 1514 return socket.inet_ntoa(struct.pack('>I', bits))515516517def 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 True526527528def 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.531532 :rtype: bool533 """534 if string_network.count('/') == 1:535 try:536 mask = int(string_network.split('/')[1])537 except ValueError:
11 unmodified lines
549 return True550551552def should_bypass_proxies(url):526 """Returns whether we should bypass proxies or not."""553 """554 Returns whether we should bypass proxies or not.555556 :rtype: bool557 """558 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())559560 # 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 lines
603 return False604605606def get_environ_proxies(url):576 """Return a dict of environment proxies."""607 """608 Return a dict of environment proxies.609610 :rtype: dict611 """612 if should_bypass_proxies(url):613 return {}614 else:615 return getproxies()
25 unmodified lines
641 return proxy642643644def 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.647648 :rtype: str649 """650 return '%s/%s' % (name, __version__)651652653def 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 lines
665def parse_header_links(value):666 """Return a dict of parsed link headers proxies.667668 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"669670 :rtype: list671 """672673 links = []674
26 unmodified lines
701_null3 = _null * 3702703704def 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 lines
735736def 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.739740 :rtype: str741 """742 scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)743744 # urlparse is a finicky beast, and sometimes decides that there isn't a
7 unmodified lines
752753def get_auth_from_url(url):754 """Given a url with authentication components, extract them into a tuple of755 username,password.756757 :rtype: (str,str)758 """759 parsed = urlparse(url)760761 try:
45 unmodified lines
807 "not %s" % (value, type(value)))808809810def 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.813814 :rtype: str815 """816 scheme, netloc, path, params, query, fragment = urlparse(url)817818 # see func:`prepend_scheme_if_needed`819 if not netloc:
5 unmodified lines