Skip to content
Myr

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

8 files+51 added−24 removed

added:requests/_internal_utils.py+27 added
1# -*- coding: utf-8 -*-23"""4requests._internal_utils5~~~~~~~~~~~~~~67Provides utility functions that are consumed internally by Requests8which depend on extremely few external helpers (such as compat)9"""1011from .compat import is_py2, builtin_str121314def 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)2627 return out
modified:requests/auth.py+2 added-1 removed
15 unmodified lines
16from base64 import b64encode1718from .compat import urlparse, str19from .cookies import extract_cookies_to_jar20from .utils import parse_dict_header, to_native_string20from ._internal_utils import to_native_string21from .utils import parse_dict_header22from .status_codes import codes2324CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'25CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
228 unmodified lines
modified:requests/cookies.py+3 added-1 removed
11 unmodified lines
12import copy13import time14import calendar15import collections1617from ._internal_utils import to_native_string18from .compat import cookielib, urlparse, urlunparse, Morsel1920try:21 import threading
34 unmodified lines
56 # 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 lines
modified:requests/models.py+2 added-2 removed
27 unmodified lines
28 DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)29from .exceptions import (30 HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,31 ContentDecodingError, ConnectionError, StreamConsumedError)32from ._internal_utils import to_native_string33from .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)37from .compat import (38 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,39 is_py2, chardet, builtin_str, basestring)40from .compat import json as complexjson
845 unmodified lines
modified:requests/sessions.py+2 added-1 removed
15 unmodified lines
16from .cookies import (17 cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)18from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT19from .hooks import default_hooks, dispatch_hook20from .utils import to_key_val_list, default_headers, to_native_string20from ._internal_utils import to_native_string21from .utils import to_key_val_list, default_headers22from .exceptions import (23 TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)24from .packages.urllib3._collections import RecentlyUsedContainer25from .structures import CaseInsensitiveDict
688 unmodified lines
modified:requests/utils.py+4 added-19 removed
18 unmodified lines
19import warnings2021from . import __version__22from . import certs23# to_native_string is unused here, but imported here for backwards compatibility24from ._internal_utils import to_native_string25from .compat import parse_http_list as _parse_list_header24from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2,25 builtin_str, getproxies, proxy_bypass, urlunparse,26 basestring)26from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote,27 getproxies, proxy_bypass, urlunparse, basestring)28from .cookies import RequestsCookieJar, cookiejar_from_dict29from .structures import CaseInsensitiveDict30from .exceptions import InvalidURL, InvalidHeader, FileModeWarning31
738 unmodified lines
770771 return auth772773773def 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)785786 return out787788774# 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 lines
modified:tests/test_requests.py+10 added
856 unmodified lines
857 s = requests.Session()858 prep = s.prepare_request(req)859 assert prep.url == "https://httpbin.org/"860861 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'870871 def test_links(self):872 r = requests.Response()873 r.headers = {874 'cache-control': 'public, max-age=60, s-maxage=60',
1015 unmodified lines
modified:AUTHORS.rst+1 added
167 unmodified lines
168- 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>`_)