module documentation

requests.utils ~~~~~~~~~~~~~~ This module provides utility functions that are used within Requests that are also useful for external consumption.

Function add_dict_to_cookiejar Returns a CookieJar from a key/value dictionary.
Function address_in_network This function allows you to check if an IP belongs to a network subnet
Function atomic_open Write a file to the disk in an atomic fashion
Function check_header_validity Verifies that header parts don't contain leading whitespace reserved characters, or return characters.
Function default_headers :rtype: requests.structures.CaseInsensitiveDict
Function default_user_agent Return a string representing the default user agent.
Function dict_from_cookiejar Returns a key/value dictionary from a CookieJar.
Function dict_to_sequence Returns an internal sequence dictionary update.
Function dotted_netmask Converts mask from /xx format to xxx.xxx.xxx.xxx
Function extract_zipped_paths Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged.
Function from_key_val_list Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g.,
Function get_auth_from_url Given a url with authentication components, extract them into a tuple of username,password.
Function get_encoding_from_headers Returns encodings from given HTTP Header Dict.
Function get_encodings_from_content Returns encodings from given content string.
Function get_environ_proxies Return a dict of environment proxies.
Function get_netrc_auth Returns the Requests tuple auth for a given url from netrc.
Function get_unicode_from_response Returns the requested content back in unicode.
Function guess_filename Tries to guess the filename of the given object.
Function guess_json_utf :rtype: str
Function is_ipv4_address :rtype: bool
Function is_valid_cidr Very simple check of the cidr format in no_proxy variable.
Function iter_slices Iterate over slices of a string.
Function parse_dict_header Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict:
Function parse_header_links Return a list of parsed link headers proxies.
Function parse_list_header Parse lists as described by RFC 2068 Section 2.
Function prepend_scheme_if_needed Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument.
Function proxy_bypass Return True, if the host should be bypassed.
Function proxy_bypass_registry Undocumented
Function requote_uri Re-quote the given URI.
Function resolve_proxies This method takes proxy information from a request and configuration input to resolve a mapping of target proxies. This will consider settings such a NO_PROXY to strip proxy configurations.
Function rewind_body Move file pointer back to its recorded starting position so it can be read again on redirect.
Function select_proxy Select a proxy for the url, if applicable.
Function set_environ Set the environment variable 'env_name' to 'value'
Function should_bypass_proxies Returns whether we should bypass proxies or not.
Function stream_decode_response_unicode Stream decodes an iterator.
Function super_len Undocumented
Function to_key_val_list Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g.,
Function unquote_header_value Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting.
Function unquote_unreserved Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
Function urldefragauth Given a url remove the fragment and the authentication part.
Constant DEFAULT_ACCEPT_ENCODING Undocumented
Constant DEFAULT_CA_BUNDLE_PATH Undocumented
Constant DEFAULT_PORTS Undocumented
Constant NETRC_FILES Undocumented
Constant UNRESERVED_SET Undocumented
Function _parse_content_type_header Returns content type and parameters from given header
Function _validate_header_part Undocumented
Variable _null Undocumented
Variable _null2 Undocumented
Variable _null3 Undocumented
def add_dict_to_cookiejar(cj, cookie_dict): (source)

Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. :rtype: CookieJar

def address_in_network(ip, net): (source)

This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool

@contextlib.contextmanager
def atomic_open(filename): (source)

Write a file to the disk in an atomic fashion

def check_header_validity(header): (source)

Verifies that header parts don't contain leading whitespace reserved characters, or return characters. :param header: tuple, in the format (name, value).

def default_headers(): (source)

:rtype: requests.structures.CaseInsensitiveDict

def default_user_agent(name='python-requests'): (source)

Return a string representing the default user agent. :rtype: str

def dict_from_cookiejar(cj): (source)

Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict

def dict_to_sequence(d): (source)

Returns an internal sequence dictionary update.

def dotted_netmask(mask): (source)

Converts mask from /xx format to xxx.xxx.xxx.xxx Example: if mask is 24 function returns 255.255.255.0 :rtype: str

def extract_zipped_paths(path): (source)

Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged.

def from_key_val_list(value): (source)

Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict

def get_auth_from_url(url): (source)

Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str)

def get_encoding_from_headers(headers): (source)

Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str

def get_encodings_from_content(content): (source)

Returns encodings from given content string. :param content: bytestring to extract encodings from.

def get_environ_proxies(url, no_proxy=None): (source)

Return a dict of environment proxies. :rtype: dict

def get_netrc_auth(url, raise_errors=False): (source)

Returns the Requests tuple auth for a given url from netrc.

def get_unicode_from_response(r): (source)

Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str

def guess_filename(obj): (source)

Tries to guess the filename of the given object.

def guess_json_utf(data): (source)

:rtype: str

def is_ipv4_address(string_ip): (source)

:rtype: bool

def is_valid_cidr(string_network): (source)

Very simple check of the cidr format in no_proxy variable. :rtype: bool

def iter_slices(string, slice_length): (source)

Iterate over slices of a string.

def parse_dict_header(value): (source)

Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict

def parse_header_links(value): (source)

Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list

def parse_list_header(value): (source)

Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list

def prepend_scheme_if_needed(url, new_scheme): (source)

Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str

def proxy_bypass(host): (source)

Return True, if the host should be bypassed. Checks proxy settings gathered from the environment, if specified, or the registry.

def proxy_bypass_registry(host): (source)

Undocumented

def requote_uri(uri): (source)

Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str

def resolve_proxies(request, proxies, trust_env=True): (source)

This method takes proxy information from a request and configuration input to resolve a mapping of target proxies. This will consider settings such a NO_PROXY to strip proxy configurations. :param request: Request or PreparedRequest :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs :param trust_env: Boolean declaring whether to trust environment configs :rtype: dict

def rewind_body(prepared_request): (source)

Move file pointer back to its recorded starting position so it can be read again on redirect.

def select_proxy(url, proxies): (source)

Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs

@contextlib.contextmanager
def set_environ(env_name, value): (source)

Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing

def should_bypass_proxies(url, no_proxy): (source)

Returns whether we should bypass proxies or not. :rtype: bool

def stream_decode_response_unicode(iterator, r): (source)

Stream decodes an iterator.

def super_len(o): (source)

Undocumented

def to_key_val_list(value): (source)

Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples :rtype: list

def unquote_header_value(value, is_filename=False): (source)

Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str

def unquote_unreserved(uri): (source)

Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str

def urldefragauth(url): (source)

Given a url remove the fragment and the authentication part. :rtype: str

DEFAULT_ACCEPT_ENCODING = (source)

Undocumented

Value
""", """.join(re.split(',\\s*',
                       make_headers(accept_encoding=True)['accept-encoding']))
DEFAULT_CA_BUNDLE_PATH = (source)

Undocumented

Value
certs.where()
DEFAULT_PORTS: dict[str, int] = (source)

Undocumented

Value
{'http': 80, 'https': 443}
NETRC_FILES: tuple[str, ...] = (source)

Undocumented

Value
('.netrc', '_netrc')
UNRESERVED_SET = (source)

Undocumented

Value
frozenset('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'+'0123456789-._~'
)
def _parse_content_type_header(header): (source)

Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters

def _validate_header_part(header_part, header_kind, validator): (source)

Undocumented

Undocumented

Undocumented

Undocumented