|
1 | 1 | # This file was auto-generated by Fern from our API Definition. |
2 | 2 |
|
3 | | -from typing import IO, Dict, List, Mapping, Optional, Tuple, Union, cast |
| 3 | +from typing import IO, Any, Dict, List, Mapping, Optional, Tuple, Union, cast |
| 4 | + |
| 5 | +try: |
| 6 | + import aiohttp |
| 7 | + HAS_AIOHTTP = True |
| 8 | +except ImportError: |
| 9 | + HAS_AIOHTTP = False |
4 | 10 |
|
5 | 11 | # File typing inspired by the flexibility of types within the httpx library |
6 | 12 | # https://github.com/encode/httpx/blob/master/httpx/_types.py |
@@ -65,3 +71,52 @@ def with_content_type(*, file: File, default_content_type: str) -> File: |
65 | 71 | else: |
66 | 72 | raise ValueError(f"Unexpected tuple length: {len(file)}") |
67 | 73 | return (None, file, default_content_type) |
| 74 | + |
| 75 | + |
| 76 | +def build_aiohttp_form_data( |
| 77 | + files: Dict[str, Union[File, List[File]]], |
| 78 | + data: Optional[Any] = None, |
| 79 | +) -> "aiohttp.FormData": |
| 80 | + """ |
| 81 | + Convert file dict to aiohttp FormData format. |
| 82 | + Similar to convert_file_dict_to_httpx_tuples but for aiohttp. |
| 83 | + """ |
| 84 | + if not HAS_AIOHTTP: |
| 85 | + raise ImportError("aiohttp is required for async file uploads") |
| 86 | + |
| 87 | + form = aiohttp.FormData() |
| 88 | + |
| 89 | + # Add regular data fields first |
| 90 | + if data is not None and isinstance(data, dict): |
| 91 | + for key, value in data.items(): |
| 92 | + if value is not None: |
| 93 | + form.add_field(key, str(value)) |
| 94 | + |
| 95 | + # Add file fields |
| 96 | + for key, file_like in files.items(): |
| 97 | + if isinstance(file_like, list): |
| 98 | + for file_item in file_like: |
| 99 | + _add_file_to_form(form, key, file_item) |
| 100 | + else: |
| 101 | + _add_file_to_form(form, key, file_like) |
| 102 | + |
| 103 | + return form |
| 104 | + |
| 105 | + |
| 106 | +def _add_file_to_form(form: "aiohttp.FormData", name: str, file: File) -> None: |
| 107 | + """Helper to add a single file to aiohttp FormData""" |
| 108 | + if isinstance(file, tuple): |
| 109 | + if len(file) == 2: |
| 110 | + filename, content = file |
| 111 | + form.add_field(name, content, filename=filename) |
| 112 | + elif len(file) == 3: |
| 113 | + filename, content, content_type = file |
| 114 | + form.add_field(name, content, filename=filename, content_type=content_type) |
| 115 | + elif len(file) == 4: |
| 116 | + filename, content, content_type, headers = file |
| 117 | + # aiohttp FormData doesn't support custom headers per field easily |
| 118 | + # Use content_type and filename |
| 119 | + form.add_field(name, content, filename=filename, content_type=content_type) |
| 120 | + else: |
| 121 | + # Simple file content |
| 122 | + form.add_field(name, file) |
0 commit comments