| 1 |
|
| 2 |
|
| 3 |
from typing import IO, Dict, List, Mapping, Optional, Tuple, Union, cast |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
FileContent = Union[IO[bytes], bytes, str] |
| 8 |
File = Union[ |
| 9 |
|
| 10 |
FileContent, |
| 11 |
|
| 12 |
Tuple[Optional[str], FileContent], |
| 13 |
|
| 14 |
Tuple[Optional[str], FileContent, Optional[str]], |
| 15 |
|
| 16 |
Tuple[ |
| 17 |
Optional[str], |
| 18 |
FileContent, |
| 19 |
Optional[str], |
| 20 |
Mapping[str, str], |
| 21 |
], |
| 22 |
] |
| 23 |
|
| 24 |
|
| 25 |
def convert_file_dict_to_httpx_tuples( |
| 26 |
d: Dict[str, Union[File, List[File]]], |
| 27 |
) -> List[Tuple[str, File]]: |
| 28 |
""" |
| 29 |
The format we use is a list of tuples, where the first element is the |
| 30 |
name of the file and the second is the file object. Typically HTTPX wants |
| 31 |
a dict, but to be able to send lists of files, you have to use the list |
| 32 |
approach (which also works for non-lists) |
| 33 |
https://github.com/encode/httpx/pull/1032 |
| 34 |
""" |
| 35 |
|
| 36 |
httpx_tuples = [] |
| 37 |
for key, file_like in d.items(): |
| 38 |
if isinstance(file_like, list): |
| 39 |
for file_like_item in file_like: |
| 40 |
httpx_tuples.append((key, file_like_item)) |
| 41 |
else: |
| 42 |
httpx_tuples.append((key, file_like)) |
| 43 |
return httpx_tuples |
| 44 |
|
| 45 |
|
| 46 |
def with_content_type(*, file: File, default_content_type: str) -> File: |
| 47 |
""" |
| 48 |
This function resolves to the file's content type, if provided, and defaults |
| 49 |
to the default_content_type value if not. |
| 50 |
""" |
| 51 |
if isinstance(file, tuple): |
| 52 |
if len(file) == 2: |
| 53 |
filename, content = cast(Tuple[Optional[str], FileContent], file) |
| 54 |
return (filename, content, default_content_type) |
| 55 |
elif len(file) == 3: |
| 56 |
filename, content, file_content_type = cast(Tuple[Optional[str], FileContent, Optional[str]], file) |
| 57 |
out_content_type = file_content_type or default_content_type |
| 58 |
return (filename, content, out_content_type) |
| 59 |
elif len(file) == 4: |
| 60 |
filename, content, file_content_type, headers = cast( |
| 61 |
Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], file |
| 62 |
) |
| 63 |
out_content_type = file_content_type or default_content_type |
| 64 |
return (filename, content, out_content_type, headers) |
| 65 |
else: |
| 66 |
raise ValueError(f"Unexpected tuple length: {len(file)}") |
| 67 |
return (None, file, default_content_type) |