codekingpro/portable-devtools
114k
1"""2requests._internal_utils3~~~~~~~~~~~~~~4 5Provides utility functions that are consumed internally by Requests6which depend on extremely few external helpers (such as compat)7"""8import re9 10from .compat import builtin_str11 12_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")13_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$")14_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$")15_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$")16 17_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR)18_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE)19HEADER_VALIDATORS = {20 bytes: _HEADER_VALIDATORS_BYTE,21 str: _HEADER_VALIDATORS_STR,22}23 24 25def to_native_string(string, encoding="ascii"):26 """Given a string object, regardless of type, returns a representation of27 that string in the native string type, encoding and decoding where28 necessary. This assumes ASCII unless told otherwise.29 """30 if isinstance(string, builtin_str):31 out = string32 else:33 out = string.decode(encoding)34 35 return out36 37 38def unicode_is_ascii(u_string):39 """Determine if unicode string only contains ASCII characters.40 41 :param str u_string: unicode string to check. Must be unicode42 and not Python 2 `str`.43 :rtype: bool44 """45 assert isinstance(u_string, str)46 try:47 u_string.encode("ascii")48 return True49 except UnicodeEncodeError:50 return False51 