diff --git a/requests/_internal_utils.py b/requests/_internal_utils.py new file mode 100644 index 00000000..0456017c --- /dev/null +++ b/requests/_internal_utils.py @@ -0,0 +1,17 @@ +from .compat import is_py2, builtin_str + + +def to_native_string(string, encoding='ascii'): + """Given a string object, regardless of type, returns a representation of + that string in the native string type, encoding and decoding where + necessary. This assumes ASCII unless told otherwise. + """ + if isinstance(string, builtin_str): + out = string + else: + if is_py2: + out = string.encode(encoding) + else: + out = string.decode(encoding) + + return out diff --git a/requests/cookies.py b/requests/cookies.py index 4a6bedd0..856fd45e 100644 --- a/requests/cookies.py +++ b/requests/cookies.py @@ -14,7 +14,7 @@ import time import calendar import collections -from . import utils +from ._internal_utils import to_native_string from .compat import cookielib, urlparse, urlunparse, Morsel try: @@ -57,7 +57,7 @@ class MockRequest(object): if not self._r.headers.get('Host'): return self._r.url # If they did set it, retrieve it and reconstruct the expected domain - host = utils.to_native_string(self._r.headers['Host'], encoding='utf-8') + host = to_native_string(self._r.headers['Host'], encoding='utf-8') parsed = urlparse(self._r.url) # Reconstruct the URL as we expect it return urlunparse([ diff --git a/requests/utils.py b/requests/utils.py index 4b2126e6..f7d4e37f 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -20,10 +20,11 @@ import warnings from . import __version__ from . import certs +# noinspection PyUnresolvedReferences +from ._internal_utils import to_native_string from .compat import parse_http_list as _parse_list_header -from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2, - builtin_str, getproxies, proxy_bypass, urlunparse, - basestring) +from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, + getproxies, proxy_bypass, urlunparse, basestring) from .cookies import RequestsCookieJar, cookiejar_from_dict from .structures import CaseInsensitiveDict from .exceptions import InvalidURL, InvalidHeader, FileModeWarning @@ -770,22 +771,6 @@ def get_auth_from_url(url): return auth -def to_native_string(string, encoding='ascii'): - """Given a string object, regardless of type, returns a representation of - that string in the native string type, encoding and decoding where - necessary. This assumes ASCII unless told otherwise. - """ - if isinstance(string, builtin_str): - out = string - else: - if is_py2: - out = string.encode(encoding) - else: - out = string.decode(encoding) - - return out - - # Moved outside of function to avoid recompile every call _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$') _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')