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