jpayne@7: from __future__ import annotations jpayne@7: jpayne@7: import email.utils jpayne@7: import mimetypes jpayne@7: import typing jpayne@7: jpayne@7: _TYPE_FIELD_VALUE = typing.Union[str, bytes] jpayne@7: _TYPE_FIELD_VALUE_TUPLE = typing.Union[ jpayne@7: _TYPE_FIELD_VALUE, jpayne@7: typing.Tuple[str, _TYPE_FIELD_VALUE], jpayne@7: typing.Tuple[str, _TYPE_FIELD_VALUE, str], jpayne@7: ] jpayne@7: jpayne@7: jpayne@7: def guess_content_type( jpayne@7: filename: str | None, default: str = "application/octet-stream" jpayne@7: ) -> str: jpayne@7: """ jpayne@7: Guess the "Content-Type" of a file. jpayne@7: jpayne@7: :param filename: jpayne@7: The filename to guess the "Content-Type" of using :mod:`mimetypes`. jpayne@7: :param default: jpayne@7: If no "Content-Type" can be guessed, default to `default`. jpayne@7: """ jpayne@7: if filename: jpayne@7: return mimetypes.guess_type(filename)[0] or default jpayne@7: return default jpayne@7: jpayne@7: jpayne@7: def format_header_param_rfc2231(name: str, value: _TYPE_FIELD_VALUE) -> str: jpayne@7: """ jpayne@7: Helper function to format and quote a single header parameter using the jpayne@7: strategy defined in RFC 2231. jpayne@7: jpayne@7: Particularly useful for header parameters which might contain jpayne@7: non-ASCII values, like file names. This follows jpayne@7: `RFC 2388 Section 4.4 `_. jpayne@7: jpayne@7: :param name: jpayne@7: The name of the parameter, a string expected to be ASCII only. jpayne@7: :param value: jpayne@7: The value of the parameter, provided as ``bytes`` or `str``. jpayne@7: :returns: jpayne@7: An RFC-2231-formatted unicode string. jpayne@7: jpayne@7: .. deprecated:: 2.0.0 jpayne@7: Will be removed in urllib3 v2.1.0. This is not valid for jpayne@7: ``multipart/form-data`` header parameters. jpayne@7: """ jpayne@7: import warnings jpayne@7: jpayne@7: warnings.warn( jpayne@7: "'format_header_param_rfc2231' is deprecated and will be " jpayne@7: "removed in urllib3 v2.1.0. This is not valid for " jpayne@7: "multipart/form-data header parameters.", jpayne@7: DeprecationWarning, jpayne@7: stacklevel=2, jpayne@7: ) jpayne@7: jpayne@7: if isinstance(value, bytes): jpayne@7: value = value.decode("utf-8") jpayne@7: jpayne@7: if not any(ch in value for ch in '"\\\r\n'): jpayne@7: result = f'{name}="{value}"' jpayne@7: try: jpayne@7: result.encode("ascii") jpayne@7: except (UnicodeEncodeError, UnicodeDecodeError): jpayne@7: pass jpayne@7: else: jpayne@7: return result jpayne@7: jpayne@7: value = email.utils.encode_rfc2231(value, "utf-8") jpayne@7: value = f"{name}*={value}" jpayne@7: jpayne@7: return value jpayne@7: jpayne@7: jpayne@7: def format_multipart_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str: jpayne@7: """ jpayne@7: Format and quote a single multipart header parameter. jpayne@7: jpayne@7: This follows the `WHATWG HTML Standard`_ as of 2021/06/10, matching jpayne@7: the behavior of current browser and curl versions. Values are jpayne@7: assumed to be UTF-8. The ``\\n``, ``\\r``, and ``"`` characters are jpayne@7: percent encoded. jpayne@7: jpayne@7: .. _WHATWG HTML Standard: jpayne@7: https://html.spec.whatwg.org/multipage/ jpayne@7: form-control-infrastructure.html#multipart-form-data jpayne@7: jpayne@7: :param name: jpayne@7: The name of the parameter, an ASCII-only ``str``. jpayne@7: :param value: jpayne@7: The value of the parameter, a ``str`` or UTF-8 encoded jpayne@7: ``bytes``. jpayne@7: :returns: jpayne@7: A string ``name="value"`` with the escaped value. jpayne@7: jpayne@7: .. versionchanged:: 2.0.0 jpayne@7: Matches the WHATWG HTML Standard as of 2021/06/10. Control jpayne@7: characters are no longer percent encoded. jpayne@7: jpayne@7: .. versionchanged:: 2.0.0 jpayne@7: Renamed from ``format_header_param_html5`` and jpayne@7: ``format_header_param``. The old names will be removed in jpayne@7: urllib3 v2.1.0. jpayne@7: """ jpayne@7: if isinstance(value, bytes): jpayne@7: value = value.decode("utf-8") jpayne@7: jpayne@7: # percent encode \n \r " jpayne@7: value = value.translate({10: "%0A", 13: "%0D", 34: "%22"}) jpayne@7: return f'{name}="{value}"' jpayne@7: jpayne@7: jpayne@7: def format_header_param_html5(name: str, value: _TYPE_FIELD_VALUE) -> str: jpayne@7: """ jpayne@7: .. deprecated:: 2.0.0 jpayne@7: Renamed to :func:`format_multipart_header_param`. Will be jpayne@7: removed in urllib3 v2.1.0. jpayne@7: """ jpayne@7: import warnings jpayne@7: jpayne@7: warnings.warn( jpayne@7: "'format_header_param_html5' has been renamed to " jpayne@7: "'format_multipart_header_param'. The old name will be " jpayne@7: "removed in urllib3 v2.1.0.", jpayne@7: DeprecationWarning, jpayne@7: stacklevel=2, jpayne@7: ) jpayne@7: return format_multipart_header_param(name, value) jpayne@7: jpayne@7: jpayne@7: def format_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str: jpayne@7: """ jpayne@7: .. deprecated:: 2.0.0 jpayne@7: Renamed to :func:`format_multipart_header_param`. Will be jpayne@7: removed in urllib3 v2.1.0. jpayne@7: """ jpayne@7: import warnings jpayne@7: jpayne@7: warnings.warn( jpayne@7: "'format_header_param' has been renamed to " jpayne@7: "'format_multipart_header_param'. The old name will be " jpayne@7: "removed in urllib3 v2.1.0.", jpayne@7: DeprecationWarning, jpayne@7: stacklevel=2, jpayne@7: ) jpayne@7: return format_multipart_header_param(name, value) jpayne@7: jpayne@7: jpayne@7: class RequestField: jpayne@7: """ jpayne@7: A data container for request body parameters. jpayne@7: jpayne@7: :param name: jpayne@7: The name of this request field. Must be unicode. jpayne@7: :param data: jpayne@7: The data/value body. jpayne@7: :param filename: jpayne@7: An optional filename of the request field. Must be unicode. jpayne@7: :param headers: jpayne@7: An optional dict-like object of headers to initially use for the field. jpayne@7: jpayne@7: .. versionchanged:: 2.0.0 jpayne@7: The ``header_formatter`` parameter is deprecated and will jpayne@7: be removed in urllib3 v2.1.0. jpayne@7: """ jpayne@7: jpayne@7: def __init__( jpayne@7: self, jpayne@7: name: str, jpayne@7: data: _TYPE_FIELD_VALUE, jpayne@7: filename: str | None = None, jpayne@7: headers: typing.Mapping[str, str] | None = None, jpayne@7: header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None, jpayne@7: ): jpayne@7: self._name = name jpayne@7: self._filename = filename jpayne@7: self.data = data jpayne@7: self.headers: dict[str, str | None] = {} jpayne@7: if headers: jpayne@7: self.headers = dict(headers) jpayne@7: jpayne@7: if header_formatter is not None: jpayne@7: import warnings jpayne@7: jpayne@7: warnings.warn( jpayne@7: "The 'header_formatter' parameter is deprecated and " jpayne@7: "will be removed in urllib3 v2.1.0.", jpayne@7: DeprecationWarning, jpayne@7: stacklevel=2, jpayne@7: ) jpayne@7: self.header_formatter = header_formatter jpayne@7: else: jpayne@7: self.header_formatter = format_multipart_header_param jpayne@7: jpayne@7: @classmethod jpayne@7: def from_tuples( jpayne@7: cls, jpayne@7: fieldname: str, jpayne@7: value: _TYPE_FIELD_VALUE_TUPLE, jpayne@7: header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None, jpayne@7: ) -> RequestField: jpayne@7: """ jpayne@7: A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. jpayne@7: jpayne@7: Supports constructing :class:`~urllib3.fields.RequestField` from jpayne@7: parameter of key/value strings AND key/filetuple. A filetuple is a jpayne@7: (filename, data, MIME type) tuple where the MIME type is optional. jpayne@7: For example:: jpayne@7: jpayne@7: 'foo': 'bar', jpayne@7: 'fakefile': ('foofile.txt', 'contents of foofile'), jpayne@7: 'realfile': ('barfile.txt', open('realfile').read()), jpayne@7: 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), jpayne@7: 'nonamefile': 'contents of nonamefile field', jpayne@7: jpayne@7: Field names and filenames must be unicode. jpayne@7: """ jpayne@7: filename: str | None jpayne@7: content_type: str | None jpayne@7: data: _TYPE_FIELD_VALUE jpayne@7: jpayne@7: if isinstance(value, tuple): jpayne@7: if len(value) == 3: jpayne@7: filename, data, content_type = value jpayne@7: else: jpayne@7: filename, data = value jpayne@7: content_type = guess_content_type(filename) jpayne@7: else: jpayne@7: filename = None jpayne@7: content_type = None jpayne@7: data = value jpayne@7: jpayne@7: request_param = cls( jpayne@7: fieldname, data, filename=filename, header_formatter=header_formatter jpayne@7: ) jpayne@7: request_param.make_multipart(content_type=content_type) jpayne@7: jpayne@7: return request_param jpayne@7: jpayne@7: def _render_part(self, name: str, value: _TYPE_FIELD_VALUE) -> str: jpayne@7: """ jpayne@7: Override this method to change how each multipart header jpayne@7: parameter is formatted. By default, this calls jpayne@7: :func:`format_multipart_header_param`. jpayne@7: jpayne@7: :param name: jpayne@7: The name of the parameter, an ASCII-only ``str``. jpayne@7: :param value: jpayne@7: The value of the parameter, a ``str`` or UTF-8 encoded jpayne@7: ``bytes``. jpayne@7: jpayne@7: :meta public: jpayne@7: """ jpayne@7: return self.header_formatter(name, value) jpayne@7: jpayne@7: def _render_parts( jpayne@7: self, jpayne@7: header_parts: ( jpayne@7: dict[str, _TYPE_FIELD_VALUE | None] jpayne@7: | typing.Sequence[tuple[str, _TYPE_FIELD_VALUE | None]] jpayne@7: ), jpayne@7: ) -> str: jpayne@7: """ jpayne@7: Helper function to format and quote a single header. jpayne@7: jpayne@7: Useful for single headers that are composed of multiple items. E.g., jpayne@7: 'Content-Disposition' fields. jpayne@7: jpayne@7: :param header_parts: jpayne@7: A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format jpayne@7: as `k1="v1"; k2="v2"; ...`. jpayne@7: """ jpayne@7: iterable: typing.Iterable[tuple[str, _TYPE_FIELD_VALUE | None]] jpayne@7: jpayne@7: parts = [] jpayne@7: if isinstance(header_parts, dict): jpayne@7: iterable = header_parts.items() jpayne@7: else: jpayne@7: iterable = header_parts jpayne@7: jpayne@7: for name, value in iterable: jpayne@7: if value is not None: jpayne@7: parts.append(self._render_part(name, value)) jpayne@7: jpayne@7: return "; ".join(parts) jpayne@7: jpayne@7: def render_headers(self) -> str: jpayne@7: """ jpayne@7: Renders the headers for this request field. jpayne@7: """ jpayne@7: lines = [] jpayne@7: jpayne@7: sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"] jpayne@7: for sort_key in sort_keys: jpayne@7: if self.headers.get(sort_key, False): jpayne@7: lines.append(f"{sort_key}: {self.headers[sort_key]}") jpayne@7: jpayne@7: for header_name, header_value in self.headers.items(): jpayne@7: if header_name not in sort_keys: jpayne@7: if header_value: jpayne@7: lines.append(f"{header_name}: {header_value}") jpayne@7: jpayne@7: lines.append("\r\n") jpayne@7: return "\r\n".join(lines) jpayne@7: jpayne@7: def make_multipart( jpayne@7: self, jpayne@7: content_disposition: str | None = None, jpayne@7: content_type: str | None = None, jpayne@7: content_location: str | None = None, jpayne@7: ) -> None: jpayne@7: """ jpayne@7: Makes this request field into a multipart request field. jpayne@7: jpayne@7: This method overrides "Content-Disposition", "Content-Type" and jpayne@7: "Content-Location" headers to the request parameter. jpayne@7: jpayne@7: :param content_disposition: jpayne@7: The 'Content-Disposition' of the request body. Defaults to 'form-data' jpayne@7: :param content_type: jpayne@7: The 'Content-Type' of the request body. jpayne@7: :param content_location: jpayne@7: The 'Content-Location' of the request body. jpayne@7: jpayne@7: """ jpayne@7: content_disposition = (content_disposition or "form-data") + "; ".join( jpayne@7: [ jpayne@7: "", jpayne@7: self._render_parts( jpayne@7: (("name", self._name), ("filename", self._filename)) jpayne@7: ), jpayne@7: ] jpayne@7: ) jpayne@7: jpayne@7: self.headers["Content-Disposition"] = content_disposition jpayne@7: self.headers["Content-Type"] = content_type jpayne@7: self.headers["Content-Location"] = content_location