Multipart files tweaks (#482)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Allow filenames as None in multipart encoding * Allow str file contents in multipart encode * Some formatting changes on `advanced.md` * Document multipart file encoding in the advanced docs * Update docs/advanced.md
authored by Yeray Diaz Diaz · committed by GitHub · parent 644e8fc · Browse files · 3 files·+113 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-Authored-By: Florimond Manca <florimond.manca@gmail.com>
Diff stats
3 files+113 added−30 removed
- tests:+33 added−0 removed
- other:+80 added−30 removed
Provenance
- Commit
9ec2cfc- Tree
f9a32e8- Author
Yeray Diaz Diaz <yeraydiazdiaz@fastmail.com>- Committer
GitHub <noreply@github.com>- Parent
644e8fc
3 files changed+113 added−30 removed
modified:docs/advanced.md+66 added-15 removed
239 unmodified lines240 has not been implemented yet. To use proxies you must pass the proxy241 information at `Client` initialization.242 243 ## Timeout fine-tuning244-HTTPX offers various request timeout management options. Three types of timeouts are available: **connect** timeouts, 245-**write** timeouts and **read** timeouts.244 247-* The **connect timeout** specifies the maximum amount of time to wait until a connection to the requested host is established. 248-If HTTPX is unable to connect within this time frame, a `ConnectTimeout` exception is raised.249-* The **write timeout** specifies the maximum duration to wait for a chunk of data to be sent (for example, a chunk of the request body). 250-If HTTPX is unable to send data within this time frame, a `WriteTimeout` exception is raised.251-* The **read timeout** specifies the maximum duration to wait for a chunk of data to be received (for example, a chunk of the response body). 252-If HTTPX is unable to receive data within this time frame, a `ReadTimeout` exception is raised.245+HTTPX offers various request timeout management options. Three types of timeouts246+are available: **connect** timeouts, **write** timeouts and **read** timeouts.247 248+* The **connect timeout** specifies the maximum amount of time to wait until249+a connection to the requested host is established. If HTTPX is unable to connect250+within this time frame, a `ConnectTimeout` exception is raised.251+* The **write timeout** specifies the maximum duration to wait for a chunk of252+data to be sent (for example, a chunk of the request body). If HTTPX is unable253+to send data within this time frame, a `WriteTimeout` exception is raised.254+* The **read timeout** specifies the maximum duration to wait for a chunk of255+data to be received (for example, a chunk of the response body). If HTTPX is256+unable to receive data within this time frame, a `ReadTimeout` exception is raised.257+258 ### Setting timeouts259+260 You can set timeouts on two levels:261 262 - For a given request:263 14 unmodified lines278 ```279 280 Besides, you can pass timeouts in two forms:281 277-- A number, which sets the read, write and connect timeouts to the same value, as in the examples above. 282+- A number, which sets the read, write and connect timeouts to the same value, as in the examples above.283 - A `TimeoutConfig` instance, which allows to define the read, write and connect timeouts independently:284 285 ```python286 timeout = httpx.TimeoutConfig(282- connect_timeout=5, 283- read_timeout=10, 287+ connect_timeout=5,288+ read_timeout=10,289 write_timeout=15290 )291 292 resp = httpx.get('http://example.com/api/v1/example', timeout=timeout)293 ```294 295 ### Default timeouts296+297 By default all types of timeouts are set to 5 second.292- 298+299 ### Disabling timeouts300+294-To disable timeouts, you can pass `None` as a timeout parameter. 301+To disable timeouts, you can pass `None` as a timeout parameter.302 Note that currently this is not supported by the top-level API.303 304 ```python305 url = "http://example.com/api/v1/delay/10"5 unmodified lines311 client.get(url) # Does not timeout, returns after 10s312 313 314 timeout = httpx.TimeoutConfig(308- connect_timeout=5, 309- read_timeout=None, 315+ connect_timeout=5,316+ read_timeout=None,317 write_timeout=5318 )319 httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s320 ```321+322+## Multipart file encoding323+324+As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)325+multipart file encoding is available by passing a dictionary with the326+name of the payloads as keys and a tuple of elements as values.327+328+```python329+>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}330+>>> r = httpx.post("https://httpbin.org/post", files=files)331+>>> print(r.text)332+{333+ ...334+ "files": {335+ "upload-file": "<... binary content ...>"336+ },337+ ...338+}339+```340+341+More specifically, this tuple must have at least two elements and maximum of three:342+- The first one is an optional file name which can be set to `None`.343+- The second may be a file-like object or a string which will be automatically344+encoded in UTF-8.345+- An optional third element can be included with the346+[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)347+of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type348+based on the file name specified as the first element or the tuple, if that349+is set to `None` or it cannot be inferred from it, HTTPX will default to350+`applicaction/octet-stream`.351+352+```python353+>>> files = {'upload-file': (None, 'text content', 'text/plain')}354+>>> r = httpx.post("https://httpbin.org/post", files=files)355+>>> print(r.text)356+{357+ ...358+ "files": {},359+ "form": {360+ "upload-file": "text-content"361+ },362+ ...363+}364+```modified:httpx/multipart.py+14 added-15 removed
57 unmodified lines58 value[2] if len(value) > 2 else self.guess_content_type()59 )60 61 def guess_content_type(self) -> str:62+ if self.filename:62- return mimetypes.guess_type(self.filename)[0] or "application/octet-stream"63+ return mimetypes.guess_type(self.filename)[0] or "application/octet-stream"64+ else:65+ return "application/octet-stream"66 67 def render_headers(self) -> bytes:65- name = _format_param("name", self.name)66- filename = _format_param("filename", self.filename)68+ parts = [b"Content-Disposition: form-data; ", _format_param("name", self.name)]69+ if self.filename:70+ filename = _format_param("filename", self.filename)71+ parts.extend([b"; ", filename])72 content_type = self.content_type.encode()68- return b"".join(69- [70- b"Content-Disposition: form-data; ",71- name,72- b"; ",73- filename,74- b"\r\nContent-Type: ",75- content_type,76- b"\r\n\r\n",77- ]78- )73+ parts.extend([b"\r\nContent-Type: ", content_type, b"\r\n\r\n"])74+ return b"".join(parts)75 76 def render_data(self) -> bytes:77+ if isinstance(self.file, str):78+ content = self.file79+ else:81- content = self.file.read()80+ content = self.file.read()81 return content.encode("utf-8") if isinstance(content, str) else content82 83 84 def iter_fields(data: dict, files: dict) -> typing.Iterator[Field]:37 unmodified linesmodified:tests/test_multipart.py+33 added
125 unmodified lines126 "".format(boundary).encode("ascii")127 )128 129 130+def test_multipart_encode_files_allows_filenames_as_none():131+ files = {"file": (None, io.BytesIO(b"<file content>"))}132+ with mock.patch("os.urandom", return_value=os.urandom(16)):133+ boundary = binascii.hexlify(os.urandom(16)).decode("ascii")134+135+ body, content_type = multipart.multipart_encode(data={}, files=files)136+137+ assert content_type == f"multipart/form-data; boundary={boundary}"138+ assert body == (139+ '--{0}\r\nContent-Disposition: form-data; name="file"\r\n'140+ "Content-Type: application/octet-stream\r\n\r\n<file content>\r\n"141+ "--{0}--\r\n"142+ "".format(boundary).encode("ascii")143+ )144+145+146+def test_multipart_encode_files_allows_str_content():147+ files = {"file": ("test.txt", "<string content>", "text/plain")}148+ with mock.patch("os.urandom", return_value=os.urandom(16)):149+ boundary = binascii.hexlify(os.urandom(16)).decode("ascii")150+151+ body, content_type = multipart.multipart_encode(data={}, files=files)152+153+ assert content_type == f"multipart/form-data; boundary={boundary}"154+ assert body == (155+ '--{0}\r\nContent-Disposition: form-data; name="file"; '156+ 'filename="test.txt"\r\n'157+ "Content-Type: text/plain\r\n\r\n<string content>\r\n"158+ "--{0}--\r\n"159+ "".format(boundary).encode("ascii")160+ )161+162+163 class TestHeaderParamHTML5Formatting:164 def test_unicode(self):165 param = multipart._format_param("filename", "n\u00e4me")166 assert param == b'filename="n\xc3\xa4me"'12 unmodified lines