module documentation

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 dict​_from​_cookiejar Returns a key/value dictionary from a CookieJar.
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​_unicode​_from​_response Returns the requested content back in unicode.
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 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 value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection.
Function default​_headers
Function default​_user​_agent Return a string representing the default user agent.
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​_environ​_proxies Return a dict of environment proxies.
Function get​_netrc​_auth Returns the Requests tuple auth for a given url from netrc.
Function guess​_filename Tries to guess the filename of the given object.
Function guess​_json​_utf
Function is​_ipv4​_address
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 a 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 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 ​_CLEAN​_HEADER​_REGEX​_BYTE Undocumented
Constant ​_CLEAN​_HEADER​_REGEX​_STR Undocumented
Variable ​_null Undocumented
Variable ​_null2 Undocumented
Variable ​_null3 Undocumented
def add_dict_to_cookiejar(cj, cookie_dict):
Returns a CookieJar from a key/value dictionary.
Parameters
cjCookieJar to insert cookies into.
cookie​_dictDict of key/values to insert into CookieJar.
Returns
CookieJarUndocumented
def dict_from_cookiejar(cj):
Returns a key/value dictionary from a CookieJar.
Parameters
cjCookieJar object to extract cookies from.
Returns
dictUndocumented
def get_encoding_from_headers(headers):
Returns encodings from given HTTP Header Dict.
Parameters
headersdictionary to extract encoding from.
Returns
strUndocumented
def get_encodings_from_content(content):
Returns encodings from given content string.
Parameters
contentbytestring to extract encodings from.
def get_unicode_from_response(r):

Returns the requested content back in unicode.

Tried:

  1. charset from content-type
  2. fall back and replace all unicode characters
Parameters
rResponse object to get unicode content from.
Returns
strUndocumented
DEFAULT_ACCEPT_ENCODING =

Undocumented

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

Undocumented

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

Undocumented

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

Undocumented

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

Undocumented

Value
frozenset('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'+'0123456789-._~'
)
def _parse_content_type_header(header):
Returns content type and parameters from given header
Parameters
headerstring
Returns
tuple containing content type and dictionary of parameters
def address_in_network(ip, net):

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
Returns
boolUndocumented
@contextlib.contextmanager
def atomic_open(filename):
Write a file to the disk in an atomic fashion
def check_header_validity(header):
Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection.
Parameters
headertuple, in the format (name, value).
def default_headers():
Returns
requests.structures.CaseInsensitiveDictUndocumented
def default_user_agent(name='python-requests'):
Return a string representing the default user agent.
Returns
strUndocumented
def dict_to_sequence(d):
Returns an internal sequence dictionary update.
def dotted_netmask(mask):

Converts mask from /xx format to xxx.xxx.xxx.xxx

Example: if mask is 24 function returns 255.255.255.0

Returns
strUndocumented
def extract_zipped_paths(path):
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):

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')])
Returns
OrderedDictUndocumented
def get_auth_from_url(url):
Given a url with authentication components, extract them into a tuple of username,password.
Returns
(str,str)Undocumented
def get_environ_proxies(url, no_proxy=None):
Return a dict of environment proxies.
Returns
dictUndocumented
def get_netrc_auth(url, raise_errors=False):
Returns the Requests tuple auth for a given url from netrc.
def guess_filename(obj):
Tries to guess the filename of the given object.
def guess_json_utf(data):
Returns
strUndocumented
def is_ipv4_address(string_ip):
Returns
boolUndocumented
def is_valid_cidr(string_network):
Very simple check of the cidr format in no_proxy variable.
Returns
boolUndocumented
def iter_slices(string, slice_length):
Iterate over slices of a string.
def parse_dict_header(value):

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 dict again, use the dump_header function.

Parameters
valuea string with a dict header.
Returns
dictdict
def parse_header_links(value):

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"

Returns
listUndocumented
def parse_list_header(value):

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 parse_set_header just that items may appear multiple times and case sensitivity is preserved.

The return value is a standard list:

>>> parse_list_header('token, "quoted value"')
['token', 'quoted value']

To create a header from the list again, use the dump_header function.

Parameters
valuea string with a list header.
Returns
listlist
def prepend_scheme_if_needed(url, new_scheme):
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.
Returns
strUndocumented
def proxy_bypass(host):

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):

Undocumented

def requote_uri(uri):

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.

Returns
strUndocumented
def resolve_proxies(request, proxies, trust_env=True):
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.
Parameters
requestRequest or PreparedRequest
proxiesA dictionary of schemes or schemes and hosts to proxy URLs
trust​_envBoolean declaring whether to trust environment configs
Returns
dictUndocumented
def rewind_body(prepared_request):
Move file pointer back to its recorded starting position so it can be read again on redirect.
def select_proxy(url, proxies):
Select a proxy for the url, if applicable.
Parameters
urlThe url being for the request
proxiesA dictionary of schemes or schemes and hosts to proxy URLs
@contextlib.contextmanager
def set_environ(env_name, value):

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):
Returns whether we should bypass proxies or not.
Returns
boolUndocumented
def stream_decode_response_unicode(iterator, r):
Stream decodes a iterator.
def super_len(o):

Undocumented

def to_key_val_list(value):

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
Returns
listUndocumented
def unquote_header_value(value, is_filename=False):
Unquotes a header value. (Reversal of quote_header_value). This does not use the real unquoting but what browsers are actually using for quoting.
Parameters
valuethe header value to unquote.
is​_filenameUndocumented
Returns
strUndocumented
def unquote_unreserved(uri):
Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
Returns
strUndocumented
def urldefragauth(url):
Given a url remove the fragment and the authentication part.
Returns
strUndocumented
_CLEAN_HEADER_REGEX_BYTE =

Undocumented

Value
re.compile(rb'^\S[^\r\n]*$|$')
_CLEAN_HEADER_REGEX_STR =

Undocumented

Value
re.compile(r'^\S[^\r\n]*$|$')
_null =

Undocumented

_null2 =

Undocumented

_null3 =

Undocumented