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
Provenance
- Commit
6212e8f- Tree
7e15d39- Author
RafaelWO <38643099+RafaelWO@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
83a8518
2 files changed+37 added−34 removed
modified:httpx/_multipart.py+37 added-6 removed
1 from __future__ import annotations2 3 import io4+import mimetypes5 import os6+import re7 import typing8 from pathlib import Path9 10 from ._types import (4 unmodified lines15 RequestFiles,16 SyncByteStream,17 )18 from ._utils import (17- format_form_param,18- guess_content_type,19 peek_filelike_length,20 primitive_value_to_str,21 to_bytes,22 )23 24+_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+)31 32+33+def _format_form_param(name: str, value: str) -> bytes:34+ """35+ Encode a name/value pair within a multipart form.36+ """37+38+ def replacer(match: typing.Match[str]) -> str:39+ return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]40+41+ value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)42+ return f'{name}="{value}"'.encode()43+44+45+def _guess_content_type(filename: str | None) -> str | None:46+ """47+ Guesses the mimetype based on a filename. Defaults to `application/octet-stream`.48+49+ 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 None54+55+56 def 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 lines88 )89 90 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 lines145 filename = Path(str(getattr(value, "name", "upload"))).name146 fileobj = value147 148 if content_type is None:118- content_type = guess_content_type(filename)149+ content_type = _guess_content_type(filename)150 151 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 3rd32 unmodified lines186 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 linesmodified:httpx/_utils.py-28 removed
1 unmodified line2 3 import codecs4 import email.message5 import ipaddress6-import mimetypes6 import os7 import re8 import typing9 from urllib.request import getproxies3 unmodified lines13 if typing.TYPE_CHECKING: # pragma: no cover14 from ._urls import URL15 16 18-_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-)25-26-17 def primitive_value_to_str(value: PrimitiveData) -> str:18 """19 Coerce a primitive data type into a string value.20 18 unmodified lines39 return False40 return True41 42 53-def format_form_param(name: str, value: str) -> bytes:54- """55- Encode a name/value pair within a multipart form.56- """57-58- def replacer(match: typing.Match[str]) -> str:59- return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]60-61- value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)62- return f'{name}="{value}"'.encode()63-64-43 def 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/Link146 unmodified lines193 def unquote(value: str) -> str:194 return value[1:-1] if value[0] == value[-1] == '"' else value195 196 219-def guess_content_type(filename: str | None) -> str | None:220- if filename:221- return mimetypes.guess_type(filename)[0] or "application/octet-stream"222- return None223-224-197 def 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