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

support tuples for files #33948

Merged
merged 16 commits into from
Jan 25, 2024
Empty file.
17 changes: 13 additions & 4 deletions sdk/core/azure-core/azure/core/rest/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,16 @@
FileContent = Union[str, bytes, IO[str], IO[bytes]]
FileType = Tuple[Optional[str], FileContent]

FilesType = Union[Mapping[str, FileType], Sequence[Tuple[str, FileType]]]
FilesType = Union[
# file (or bytes)
FileContent,
# (filename, file (or bytes))
Tuple[Optional[str], FileContent],
# (filename, file (or bytes), content_type)
Tuple[Optional[str], FileContent, Optional[str]],
# (filename, file (or bytes), content_type, headers)
Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],
iscai-msft marked this conversation as resolved.
Show resolved Hide resolved
]

ContentTypeBase = Union[str, bytes, Iterable[bytes]]
ContentType = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]
Expand Down Expand Up @@ -103,9 +112,9 @@ def set_urlencoded_body(data, has_files):
default_headers["Content-Type"] = "application/x-www-form-urlencoded"
return default_headers, body


def set_multipart_body(files):
formatted_files = {f: _format_data_helper(d) for f, d in files.items() if d is not None}
def set_multipart_body(files: Union[Mapping[str, FilesType], Sequence[Tuple[str, FilesType]]]):
file_items = files.items() if isinstance(files, Mapping) else files
formatted_files = {f: _format_data_helper(d) for f, d in file_items if d is not None}
return {}, formatted_files


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
Iterator,
List,
Sequence,
Dict,
)
from http.client import HTTPConnection
from urllib.parse import urlparse
Expand Down Expand Up @@ -344,16 +345,31 @@ def _format_data_helper(data: Union[str, IO]) -> Union[Tuple[None, str], Tuple[O
:rtype: tuple[str, IO, str] or tuple[None, str]
:return: A tuple of (data name, data IO, "application/octet-stream") or (None, data str)
"""
if hasattr(data, "read"):
content_type = "application/octet-stream" # default content type
iscai-msft marked this conversation as resolved.
Show resolved Hide resolved
filename: Optional[str] = None
if isinstance(data, tuple):
if len(data) == 2:
# Filename and file bytes are included
filename, file_bytes = data
elif len(data) == 3:
# Filename, file object, and content_type are included
filename, file_bytes, content_type = data
else:
raise ValueError(
iscai-msft marked this conversation as resolved.
Show resolved Hide resolved
"Unexpected data format. Expected file, or tuple of (filename, file_bytes) or "
"(filename, file_bytes, content_type)."
)
else:
# here we just get the file content
data = cast(IO, data)
data_name = None
try:
if data.name[0] != "<" and data.name[-1] != ">":
iscai-msft marked this conversation as resolved.
Show resolved Hide resolved
data_name = os.path.basename(data.name)
filename = os.path.basename(data.name)
except (AttributeError, TypeError):
pass
return (data_name, data, "application/octet-stream")
return (None, cast(str, data))
file_bytes = data

return (filename, file_bytes, content_type)


def _aiohttp_body_helper(
Expand Down
25 changes: 25 additions & 0 deletions sdk/core/azure-core/tests/test_rest_http_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,31 @@ def test_stream_input():
data_stream = Stream(length=4)
HttpRequest(method="PUT", url="http://www.example.com", content=data_stream) # ensure we can make this HttpRequest

@pytest.fixture
def filebytes():
return open("/Users/isabellacai/Desktop/github/azure-sdk-for-python/sdk/core/azure-core/empty.py", "rb")

def test_multipart_bytes(filebytes):
request = HttpRequest("POST", url="http://example.org", files={"file": filebytes})
iscai-msft marked this conversation as resolved.
Show resolved Hide resolved

assert request.content == {"file": ("empty.py", filebytes, "application/octet-stream")}


def test_multipart_filename_and_bytes():
filebytes = open("/Users/isabellacai/Desktop/github/azure-sdk-for-python/sdk/core/azure-core/empty.py", "rb")
files = ("specifiedFileName", filebytes)
request = HttpRequest("POST", url="http://example.org", files={"file": files})

assert request.content == {"file": ("specifiedFileName", filebytes, "application/octet-stream")}

def test_multipart_filename_and_bytes_and_content_type():
filebytes = open("/Users/isabellacai/Desktop/github/azure-sdk-for-python/sdk/core/azure-core/empty.py", "rb")
files = ("specifiedFileName", filebytes, "application/json")
request = HttpRequest("POST", url="http://example.org", files={"file": files})

assert request.content == {"file": ("specifiedFileName", filebytes, "application/json")}



# NOTE: For files, we don't allow list of tuples yet, just dict. Will uncomment when we add this capability
# def test_multipart_multiple_files_single_input_content():
Expand Down
Loading