Skip to content
Myr

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

3 files+113 added−30 removed

modified:docs/advanced.md+66 added-15 removed
239 unmodified lines
240 has not been implemented yet. To use proxies you must pass the proxy241 information at `Client` initialization.242243## Timeout fine-tuning244HTTPX offers various request timeout management options. Three types of timeouts are available: **connect** timeouts, 245**write** timeouts and **read** timeouts.244247* The **connect timeout** specifies the maximum amount of time to wait until a connection to the requested host is established. 248If 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). 250If 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). 252If HTTPX is unable to receive data within this time frame, a `ReadTimeout` exception is raised.245HTTPX offers various request timeout management options. Three types of timeouts246are available: **connect** timeouts, **write** timeouts and **read** timeouts.247248* The **connect timeout** specifies the maximum amount of time to wait until249a connection to the requested host is established. If HTTPX is unable to connect250within this time frame, a `ConnectTimeout` exception is raised.251* The **write timeout** specifies the maximum duration to wait for a chunk of252data to be sent (for example, a chunk of the request body). If HTTPX is unable253to send data within this time frame, a `WriteTimeout` exception is raised.254* The **read timeout** specifies the maximum duration to wait for a chunk of255data to be received (for example, a chunk of the response body). If HTTPX is256unable to receive data within this time frame, a `ReadTimeout` exception is raised.257258### Setting timeouts259260You can set timeouts on two levels:261262- For a given request:263
14 unmodified lines
278```279280Besides, you can pass timeouts in two forms:281277- 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:284285```python286timeout = httpx.TimeoutConfig(282 connect_timeout=5, 283 read_timeout=10, 287 connect_timeout=5,288 read_timeout=10,289 write_timeout=15290)291292resp = httpx.get('http://example.com/api/v1/example', timeout=timeout)293```294295### Default timeouts296297By default all types of timeouts are set to 5 second.292 298299### Disabling timeouts300294To disable timeouts, you can pass `None` as a timeout parameter. 301To disable timeouts, you can pass `None` as a timeout parameter.302Note that currently this is not supported by the top-level API.303304```python305url = "http://example.com/api/v1/delay/10"
5 unmodified lines
311 client.get(url) # Does not timeout, returns after 10s312313314timeout = httpx.TimeoutConfig(308 connect_timeout=5, 309 read_timeout=None, 315 connect_timeout=5,316 read_timeout=None,317 write_timeout=5318)319httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s320```321322## Multipart file encoding323324As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)325multipart file encoding is available by passing a dictionary with the326name of the payloads as keys and a tuple of elements as values.327328```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```340341More 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 automatically344encoded 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)347of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type348based on the file name specified as the first element or the tuple, if that349is set to `None` or it cannot be inferred from it, HTTPX will default to350`applicaction/octet-stream`.351352```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 lines
58 value[2] if len(value) > 2 else self.guess_content_type()59 )6061 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"6667 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)7576 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 content828384def iter_fields(data: dict, files: dict) -> typing.Iterator[Field]:
37 unmodified lines
modified:tests/test_multipart.py+33 added
125 unmodified lines
126 "".format(boundary).encode("ascii")127 )128129130def 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")134135 body, content_type = multipart.multipart_encode(data={}, files=files)136137 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 )144145146def 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")150151 body, content_type = multipart.multipart_encode(data={}, files=files)152153 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 )161162163class 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