Skip to content
Myr

Move utility functions from _utils.py to _multipart.py (#3388)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by RafaelWO · committed by GitHub · parent 83a8518 · Browse files · 2 files+37 added−34 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+37 added−34 removed

  • other:+37 added−34 removed

2 files+37 added−34 removed

modified:httpx/_multipart.py+37 added-6 removed
1from __future__ import annotations23import io4import mimetypes5import os6import re7import typing8from pathlib import Path910from ._types import (
4 unmodified lines
15 RequestFiles,16 SyncByteStream,17)18from ._utils import (17 format_form_param,18 guess_content_type,19 peek_filelike_length,20 primitive_value_to_str,21 to_bytes,22)2324_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}25_HTML5_FORM_ENCODING_REPLACEMENTS.update(26 {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B}27)28_HTML5_FORM_ENCODING_RE = re.compile(29 r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])30)313233def _format_form_param(name: str, value: str) -> bytes:34 """35 Encode a name/value pair within a multipart form.36 """3738 def replacer(match: typing.Match[str]) -> str:39 return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]4041 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)42 return f'{name}="{value}"'.encode()434445def _guess_content_type(filename: str | None) -> str | None:46 """47 Guesses the mimetype based on a filename. Defaults to `application/octet-stream`.4849 Returns `None` if `filename` is `None` or empty.50 """51 if filename:52 return mimetypes.guess_type(filename)[0] or "application/octet-stream"53 return None545556def get_multipart_boundary_from_content_type(57 content_type: bytes | None,58) -> bytes | None:59 if not content_type or not content_type.startswith(b"multipart/form-data"):
28 unmodified lines
88 )8990 def render_headers(self) -> bytes:91 if not hasattr(self, "_headers"):61 name = format_form_param("name", self.name)92 name = _format_form_param("name", self.name)93 self._headers = b"".join(94 [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"]95 )96
48 unmodified lines
145 filename = Path(str(getattr(value, "name", "upload"))).name146 fileobj = value147148 if content_type is None:118 content_type = guess_content_type(filename)149 content_type = _guess_content_type(filename)150151 has_content_type_header = any("content-type" in key.lower() for key in headers)152 if content_type is not None and not has_content_type_header:153 # note that unlike requests, we ignore the content_type provided in the 3rd
32 unmodified lines
186 def render_headers(self) -> bytes:187 if not hasattr(self, "_headers"):188 parts = [189 b"Content-Disposition: form-data; ",159 format_form_param("name", self.name),190 _format_form_param("name", self.name),191 ]192 if self.filename:162 filename = format_form_param("filename", self.filename)193 filename = _format_form_param("filename", self.filename)194 parts.extend([b"; ", filename])195 for header_name, header_value in self.headers.items():196 key, val = f"\r\n{header_name}: ".encode(), header_value.encode()197 parts.extend([key, val])
103 unmodified lines
modified:httpx/_utils.py-28 removed
1 unmodified line
23import codecs4import email.message5import ipaddress6import mimetypes6import os7import re8import typing9from urllib.request import getproxies
3 unmodified lines
13if typing.TYPE_CHECKING: # pragma: no cover14 from ._urls import URL151618_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}19_HTML5_FORM_ENCODING_REPLACEMENTS.update(20 {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B}21)22_HTML5_FORM_ENCODING_RE = re.compile(23 r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])24)252617def primitive_value_to_str(value: PrimitiveData) -> str:18 """19 Coerce a primitive data type into a string value.20
18 unmodified lines
39 return False40 return True414253def format_form_param(name: str, value: str) -> bytes:54 """55 Encode a name/value pair within a multipart form.56 """5758 def replacer(match: typing.Match[str]) -> str:59 return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]6061 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)62 return f'{name}="{value}"'.encode()636443def parse_header_links(value: str) -> list[dict[str, str]]:44 """45 Returns a list of parsed link headers, for more info see:46 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
146 unmodified lines
193def unquote(value: str) -> str:194 return value[1:-1] if value[0] == value[-1] == '"' else value195196219def guess_content_type(filename: str | None) -> str | None:220 if filename:221 return mimetypes.guess_type(filename)[0] or "application/octet-stream"222 return None223224197def peek_filelike_length(stream: typing.Any) -> int | None:198 """199 Given a file-like stream object, return its length in number of bytes200 without reading it into memory.
144 unmodified lines