Merge pull request #3598 from bbamsch/bytestringHostFix
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Issue #3597 - Avoid bytestring/str hodgepodge when resolving cookie from Request URL
authored by Cory Benfield · committed by GitHub · parents 9a0b392, 087aeac · Browse files · 8 files·+51 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+51 added−24 removed
- tests:+10 added−0 removed
- other:+41 added−24 removed
Provenance
- Commit
5eabcb7- Tree
a389f2b- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9a0b392- Parent 2
087aeac
8 files changed+51 added−24 removed
added:requests/_internal_utils.py+27 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests._internal_utils5+~~~~~~~~~~~~~~6+7+Provides utility functions that are consumed internally by Requests8+which depend on extremely few external helpers (such as compat)9+"""10+11+from .compat import is_py2, builtin_str12+13+14+def to_native_string(string, encoding='ascii'):15+ """Given a string object, regardless of type, returns a representation of16+ that string in the native string type, encoding and decoding where17+ necessary. This assumes ASCII unless told otherwise.18+ """19+ if isinstance(string, builtin_str):20+ out = string21+ else:22+ if is_py2:23+ out = string.encode(encoding)24+ else:25+ out = string.decode(encoding)26+27+ return outmodified:requests/auth.py+2 added-1 removed
15 unmodified lines16 from base64 import b64encode17 18 from .compat import urlparse, str19 from .cookies import extract_cookies_to_jar20-from .utils import parse_dict_header, to_native_string20+from ._internal_utils import to_native_string21+from .utils import parse_dict_header22 from .status_codes import codes23 24 CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'25 CONTENT_TYPE_MULTI_PART = 'multipart/form-data'228 unmodified linesmodified:requests/cookies.py+3 added-1 removed
11 unmodified lines12 import copy13 import time14 import calendar15 import collections16+17+from ._internal_utils import to_native_string18 from .compat import cookielib, urlparse, urlunparse, Morsel19 20 try:21 import threading34 unmodified lines56 # header57 if not self._r.headers.get('Host'):58 return self._r.url59 # If they did set it, retrieve it and reconstruct the expected domain58- host = self._r.headers['Host']60+ host = to_native_string(self._r.headers['Host'], encoding='utf-8')61 parsed = urlparse(self._r.url)62 # Reconstruct the URL as we expect it63 return urlunparse([64 parsed.scheme, host, parsed.path, parsed.params, parsed.query,478 unmodified linesmodified:requests/models.py+2 added-2 removed
27 unmodified lines28 DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)29 from .exceptions import (30 HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,31 ContentDecodingError, ConnectionError, StreamConsumedError)32+from ._internal_utils import to_native_string33 from .utils import (34 guess_filename, get_auth_from_url, requote_uri,35 stream_decode_response_unicode, to_key_val_list, parse_header_links,35- iter_slices, guess_json_utf, super_len, to_native_string,36- check_header_validity)36+ iter_slices, guess_json_utf, super_len, check_header_validity)37 from .compat import (38 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,39 is_py2, chardet, builtin_str, basestring)40 from .compat import json as complexjson845 unmodified linesmodified:requests/sessions.py+2 added-1 removed
15 unmodified lines16 from .cookies import (17 cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)18 from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT19 from .hooks import default_hooks, dispatch_hook20-from .utils import to_key_val_list, default_headers, to_native_string20+from ._internal_utils import to_native_string21+from .utils import to_key_val_list, default_headers22 from .exceptions import (23 TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)24 from .packages.urllib3._collections import RecentlyUsedContainer25 from .structures import CaseInsensitiveDict688 unmodified linesmodified:requests/utils.py+4 added-19 removed
18 unmodified lines19 import warnings20 21 from . import __version__22 from . import certs23+# to_native_string is unused here, but imported here for backwards compatibility24+from ._internal_utils import to_native_string25 from .compat import parse_http_list as _parse_list_header24-from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2,25- builtin_str, getproxies, proxy_bypass, urlunparse,26- basestring)26+from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote,27+ getproxies, proxy_bypass, urlunparse, basestring)28 from .cookies import RequestsCookieJar, cookiejar_from_dict29 from .structures import CaseInsensitiveDict30 from .exceptions import InvalidURL, InvalidHeader, FileModeWarning31 738 unmodified lines770 771 return auth772 773 773-def to_native_string(string, encoding='ascii'):774- """Given a string object, regardless of type, returns a representation of775- that string in the native string type, encoding and decoding where776- necessary. This assumes ASCII unless told otherwise.777- """778- if isinstance(string, builtin_str):779- out = string780- else:781- if is_py2:782- out = string.encode(encoding)783- else:784- out = string.decode(encoding)785-786- return out787-788-774 # Moved outside of function to avoid recompile every call775 _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')776 _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')777 36 unmodified linesmodified:tests/test_requests.py+10 added
856 unmodified lines857 s = requests.Session()858 prep = s.prepare_request(req)859 assert prep.url == "https://httpbin.org/"860 861+ def test_request_with_bytestring_host(self):862+ s = requests.Session()863+ resp = s.request(864+ 'GET',865+ 'http://httpbin.org/cookies/set?cookie=value',866+ allow_redirects=False,867+ headers={'Host': b'httpbin.org'}868+ )869+ assert resp.cookies.get('cookie') == 'value'870+871 def test_links(self):872 r = requests.Response()873 r.headers = {874 'cache-control': 'public, max-age=60, s-maxage=60',1015 unmodified linesmodified:AUTHORS.rst+1 added
167 unmodified lines168 - Jesse Shapiro <jesse@jesseshapiro.net> (`@haikuginger <https://github.com/haikuginger>`_)169 - Nate Prewitt <nate.prewitt@gmail.com> (`@nateprewitt <https://github.com/nateprewitt>`_)170 - Maik Himstedt171 - Michael Hunsinger172+- Brian Bamsch <bbamsch32@gmail.com> (`@bbamsch <https://github.com/bbamsch>`_)