jpayne@7
|
1 """
|
jpayne@7
|
2 requests._internal_utils
|
jpayne@7
|
3 ~~~~~~~~~~~~~~
|
jpayne@7
|
4
|
jpayne@7
|
5 Provides utility functions that are consumed internally by Requests
|
jpayne@7
|
6 which depend on extremely few external helpers (such as compat)
|
jpayne@7
|
7 """
|
jpayne@7
|
8 import re
|
jpayne@7
|
9
|
jpayne@7
|
10 from .compat import builtin_str
|
jpayne@7
|
11
|
jpayne@7
|
12 _VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")
|
jpayne@7
|
13 _VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$")
|
jpayne@7
|
14 _VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$")
|
jpayne@7
|
15 _VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$")
|
jpayne@7
|
16
|
jpayne@7
|
17 _HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR)
|
jpayne@7
|
18 _HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE)
|
jpayne@7
|
19 HEADER_VALIDATORS = {
|
jpayne@7
|
20 bytes: _HEADER_VALIDATORS_BYTE,
|
jpayne@7
|
21 str: _HEADER_VALIDATORS_STR,
|
jpayne@7
|
22 }
|
jpayne@7
|
23
|
jpayne@7
|
24
|
jpayne@7
|
25 def to_native_string(string, encoding="ascii"):
|
jpayne@7
|
26 """Given a string object, regardless of type, returns a representation of
|
jpayne@7
|
27 that string in the native string type, encoding and decoding where
|
jpayne@7
|
28 necessary. This assumes ASCII unless told otherwise.
|
jpayne@7
|
29 """
|
jpayne@7
|
30 if isinstance(string, builtin_str):
|
jpayne@7
|
31 out = string
|
jpayne@7
|
32 else:
|
jpayne@7
|
33 out = string.decode(encoding)
|
jpayne@7
|
34
|
jpayne@7
|
35 return out
|
jpayne@7
|
36
|
jpayne@7
|
37
|
jpayne@7
|
38 def unicode_is_ascii(u_string):
|
jpayne@7
|
39 """Determine if unicode string only contains ASCII characters.
|
jpayne@7
|
40
|
jpayne@7
|
41 :param str u_string: unicode string to check. Must be unicode
|
jpayne@7
|
42 and not Python 2 `str`.
|
jpayne@7
|
43 :rtype: bool
|
jpayne@7
|
44 """
|
jpayne@7
|
45 assert isinstance(u_string, str)
|
jpayne@7
|
46 try:
|
jpayne@7
|
47 u_string.encode("ascii")
|
jpayne@7
|
48 return True
|
jpayne@7
|
49 except UnicodeEncodeError:
|
jpayne@7
|
50 return False
|