Allow str/bytes subclasses to be used as header parts
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Seth Michael Larson · committed by Seth Michael Larson · parent e90852d · Browse files · 3 files·+48 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+48 added−13 removed
- tests:+25 added−0 removed
- other:+23 added−13 removed
Provenance
- Commit
7f694b7- Tree
f602178- Author
Seth Michael Larson <sethmichaellarson@gmail.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
e90852d
3 files changed+48 added−13 removed
modified:requests/_internal_utils.py+4 added-2 removed
12 unmodified lines13 _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)19 HEADER_VALIDATORS = {18- bytes: (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE),19- str: (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR),20+ bytes: _HEADER_VALIDATORS_BYTE,21+ str: _HEADER_VALIDATORS_STR,22 }23 24 25 def to_native_string(string, encoding="ascii"):25 unmodified linesmodified:requests/utils.py+19 added-11 removed
23 unmodified lines24 from . import certs25 from .__version__ import __version__26 27 # to_native_string is unused here, but imported here for backwards compatibility28-from ._internal_utils import HEADER_VALIDATORS, to_native_string # noqa: F40128+from ._internal_utils import ( # noqa: F40129+ _HEADER_VALIDATORS_BYTE,30+ _HEADER_VALIDATORS_STR,31+ HEADER_VALIDATORS,32+ to_native_string,33+)34 from .compat import (35 Mapping,36 basestring,37 bytes,997 unmodified lines1035 1036 :param header: tuple, in the format (name, value).1037 """1038 name, value = header1039+ _validate_header_part(header, name, 0)1040+ _validate_header_part(header, value, 1)1041 1035- for part in header:1036- if type(part) not in HEADER_VALIDATORS:1037- raise InvalidHeader(1038- f"Header part ({part!r}) from {{{name!r}: {value!r}}} must be "1039- f"of type str or bytes, not {type(part)}"1040- )1042 1042- _validate_header_part(name, "name", HEADER_VALIDATORS[type(name)][0])1043- _validate_header_part(value, "value", HEADER_VALIDATORS[type(value)][1])1043+def _validate_header_part(header, header_part, header_validator_index):1044+ if isinstance(header_part, str):1045+ validator = _HEADER_VALIDATORS_STR[header_validator_index]1046+ elif isinstance(header_part, bytes):1047+ validator = _HEADER_VALIDATORS_BYTE[header_validator_index]1048+ else:1049+ raise InvalidHeader(1050+ f"Header part ({header_part!r}) from {header} "1051+ f"must be of type str or bytes, not {type(header_part)}"1052+ )1053 1045-1046-def _validate_header_part(header_part, header_kind, validator):1054 if not validator.match(header_part):1055+ header_kind = "name" if header_validator_index == 0 else "value"1056 raise InvalidHeader(1057 f"Invalid leading whitespace, reserved character(s), or return"1058 f"character(s) in header {header_kind}: {header_part!r}"1059 )35 unmodified linesmodified:tests/test_requests.py+25 added
1750 unmodified lines1751 """1752 with pytest.raises(InvalidHeader):1753 requests.get(httpbin("get"), headers=invalid_header)1754 1755+ def test_header_with_subclass_types(self, httpbin):1756+ """If the subclasses does not behave *exactly* like1757+ the base bytes/str classes, this is not supported.1758+ This test is for backwards compatibility.1759+ """1760+1761+ class MyString(str):1762+ pass1763+1764+ class MyBytes(bytes):1765+ pass1766+1767+ r_str = requests.get(httpbin("get"), headers={MyString("x-custom"): "myheader"})1768+ assert r_str.request.headers["x-custom"] == "myheader"1769+1770+ r_bytes = requests.get(1771+ httpbin("get"), headers={MyBytes(b"x-custom"): b"myheader"}1772+ )1773+ assert r_bytes.request.headers["x-custom"] == b"myheader"1774+1775+ r_mixed = requests.get(1776+ httpbin("get"), headers={MyString("x-custom"): MyBytes(b"myheader")}1777+ )1778+ assert r_mixed.request.headers["x-custom"] == b"myheader"1779+1780 @pytest.mark.parametrize("files", ("foo", b"foo", bytearray(b"foo")))1781 def test_can_send_objects_with_files(self, httpbin, files):1782 data = {"a": "this is a string"}1783 files = {"b": files}1007 unmodified lines