Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

single input multiple files enabled #891

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 30 additions & 22 deletions httpx/_content_streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,27 @@
)

RequestData = typing.Union[
dict, str, bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]
dict, list, str, bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]
]

RequestFiles = typing.Dict[
str,
typing.Union[
# file (or str)
FileEntry = typing.Union[
# file (or str)
typing.Union[typing.IO[str], typing.IO[bytes], StrOrBytes],
# (filename, file (or str))
typing.Tuple[
typing.Optional[str],
typing.Union[typing.IO[str], typing.IO[bytes], StrOrBytes],
# (filename, file (or str))
typing.Tuple[
typing.Optional[str],
typing.Union[typing.IO[str], typing.IO[bytes], StrOrBytes],
],
# (filename, file (or str), content_type)
typing.Tuple[
typing.Optional[str],
typing.Union[typing.IO[str], typing.IO[bytes], StrOrBytes],
typing.Optional[str],
],
],
# (filename, file (or str), content_type)
typing.Tuple[
typing.Optional[str],
typing.Union[typing.IO[str], typing.IO[bytes], StrOrBytes],
typing.Optional[str],
],
]

RequestFiles = typing.Union[
typing.Dict[str, FileEntry], typing.List[typing.Tuple[str, FileEntry]]
]


Expand Down Expand Up @@ -181,7 +182,7 @@ class URLEncodedStream(ContentStream):
Request content as URL encoded form data.
"""

def __init__(self, data: dict) -> None:
def __init__(self, data: typing.Union[dict, list]) -> None:
self.body = urlencode(data, doseq=True).encode("utf-8")

def get_headers(self) -> typing.Dict[str, str]:
Expand Down Expand Up @@ -327,7 +328,10 @@ def render(self) -> typing.Iterator[bytes]:
yield from self.render_data()

def __init__(
self, data: typing.Mapping, files: typing.Mapping, boundary: bytes = None
self,
data: typing.Union[typing.Mapping, list],
files: typing.Union[typing.Mapping, list],
boundary: bytes = None,
) -> None:
if boundary is None:
boundary = binascii.hexlify(os.urandom(16))
Expand All @@ -339,16 +343,20 @@ def __init__(
self.fields = list(self._iter_fields(data, files))

def _iter_fields(
self, data: typing.Mapping, files: typing.Mapping
self,
data: typing.Union[typing.Mapping, list],
files: typing.Union[typing.Mapping, list],
) -> typing.Iterator[typing.Union["FileField", "DataField"]]:
for name, value in data.items():
data_items = data.items() if isinstance(data, dict) else data
for name, value in data_items:
if isinstance(value, list):
for item in value:
yield self.DataField(name=name, value=item)
else:
yield self.DataField(name=name, value=value)

for name, value in files.items():
file_items = files.items() if isinstance(files, dict) else files
for name, value in file_items:
yield self.FileField(name=name, value=value)

def iter_chunks(self) -> typing.Iterator[bytes]:
Expand Down Expand Up @@ -406,7 +414,7 @@ def encode(
return MultipartStream(data={}, files=files, boundary=boundary)
else:
return ByteStream(body=b"")
elif isinstance(data, dict):
elif isinstance(data, (dict, list)):
if files:
return MultipartStream(data=data, files=files, boundary=boundary)
else:
Expand Down
62 changes: 62 additions & 0 deletions tests/test_content_streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,21 @@ async def test_urlencoded_content():
assert async_content == b"Hello=world%21"


@pytest.mark.asyncio
async def test_urlencoded_list_content():
stream = encode(data=[("Hello", "world1!"), ("Hello", "world2!")])
sync_content = b"".join([part for part in stream])
async_content = b"".join([part async for part in stream])

assert stream.can_replay()
assert stream.get_headers() == {
"Content-Length": "31",
"Content-Type": "application/x-www-form-urlencoded",
}
assert sync_content == b"Hello=world1%21&Hello=world2%21"
assert async_content == b"Hello=world1%21&Hello=world2%21"


@pytest.mark.asyncio
async def test_multipart_files_content():
files = {"file": io.BytesIO(b"<file content>")}
Expand Down Expand Up @@ -146,6 +161,53 @@ async def test_multipart_files_content():
)


@pytest.mark.asyncio
async def test_multipart_multiple_files_single_input_content():
files = [
("file", io.BytesIO(b"<file content 1>")),
("file", io.BytesIO(b"<file content 2>")),
]
stream = encode(files=files, boundary=b"+++")
sync_content = b"".join([part for part in stream])
async_content = b"".join([part async for part in stream])

assert stream.can_replay()
assert stream.get_headers() == {
"Content-Length": "271",
"Content-Type": "multipart/form-data; boundary=+++",
}
assert sync_content == b"".join(
[
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content 1>\r\n",
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content 2>\r\n",
b"--+++--\r\n",
]
)
assert async_content == b"".join(
[
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content 1>\r\n",
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content 2>\r\n",
b"--+++--\r\n",
]
)


@pytest.mark.asyncio
async def test_multipart_data_and_files_content():
data = {"message": "Hello, world!"}
Expand Down