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

Add filename parameter to MultipartBody #400

Merged
merged 5 commits into from
Oct 28, 2024
Merged
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
28 changes: 23 additions & 5 deletions packages/abstractions/kiota_abstractions/multipart_body.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,31 @@ class MultipartBody(Parsable, Generic[T]):
"""Represents a multipart body for a request or a response.
Example usage:
multipart = MultipartBody()
multipart.add_or_replace_part("file", "image/jpeg", open("image.jpg", "rb").read())
multipart.add_or_replace_part(
"file", "image/jpeg", open("image.jpg", "rb").read(), "image.jpg"
)
multipart.add_or_replace_part("text", "text/plain", "Hello, World!")
with open("output.txt", "w") as output_file:
multipart.serialize(output_file)
"""
boundary: str = str(uuid.uuid4())
parts: Dict[str, Tuple[str, Any]] = field(default_factory=dict)
parts: Dict[str, Tuple[str, Any, Optional[str]]] = field(default_factory=dict)
request_adapter: Optional[RequestAdapter] = None

def add_or_replace_part(self, part_name: str, content_type: str, part_value: T) -> None:
def add_or_replace_part(
self,
part_name: str,
content_type: str,
part_value: T,
filename: Optional[str] = None
) -> None:
"""Adds or replaces a part to the multipart body.

Args:
part_name (str): The name of the part to add or replace.
content_type (str): The content type of the part.
part_value (T): The value of the part.
filename (str, optional): The filename of the part.

Returns:
None
Expand All @@ -50,7 +59,7 @@ def add_or_replace_part(self, part_name: str, content_type: str, part_value: T)
raise ValueError("Content type cannot be null")
if not part_value:
raise ValueError("Part value cannot be null")
value: Tuple[str, Any] = (content_type, part_value)
value: Tuple[str, Any, Optional[str]] = (content_type, part_value, filename)
self.parts[self._normalize_part_name(part_name)] = value

def get_part_value(self, part_name: str) -> Optional[T]:
Expand Down Expand Up @@ -104,7 +113,9 @@ def serialize(self, writer: SerializationWriter) -> None:

writer.write_str_value("", f"--{self.boundary}")
writer.write_str_value("Content-Type", f"{part_value[0]}")
writer.write_str_value("Content-Disposition", f'form-data; name="{part_name}"')
writer.write_str_value(
"Content-Disposition", self._get_comtent_disposition(part_name, part_value)
)
self._add_new_line(writer)

if isinstance(part_value[1], Parsable):
Expand All @@ -127,6 +138,13 @@ def _normalize_part_name(self, original: str) -> str:
def _add_new_line(self, writer: SerializationWriter) -> None:
writer.write_str_value("", "")

def _get_comtent_disposition(
self, part_name: str, part_value: Tuple[str, Any, Optional[str]]
) -> str:
if len(part_value) >= 3 and part_value[2] is not None:
return f'form-data; name="{part_name}"; filename="{part_value[2]}"'
return f'form-data; name="{part_name}"'

def _write_parsable(self, writer, part_value) -> None:
if not self.request_adapter or not self.request_adapter.get_serialization_writer_factory():
raise ValueError("Request adapter or serialization writer factory cannot be null")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,16 @@ def test_write_object_value_inverted(user_1, mock_request_adapter, mock_serializ
serialization_writer.write_object_value("", mock_multipart_body, None)
content = serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == f'--{mock_multipart_body.boundary}'+'\r\nContent-Type: application/octet-stream\r\nContent-Disposition: form-data; name="img"\r\n\r\nHello world\r\n'+f'--{mock_multipart_body.boundary}'+'\r\nContent-Type: application/json\r\nContent-Disposition: form-data; name="test user"\r\n\r\n{"id": "eac79bd3-fd08-4abf-9df2-2565cf3a3845", "workDuration": "2:00:00", "birthDay": "2017-09-04", "startWorkTime": "00:00:00", "createdDateTime": "2022-01-27T12:59:45", "businessPhones": ["+1 412 555 0109"], "mobilePhone": null, "accountEnabled": false, "jobTitle": "Auditor", "manager": {"id": "eac79bd3-fd08-4abf-9df2-2565cf3a3845"}}\r\n'+f'--{mock_multipart_body.boundary}--\r\n'
assert content_string == f'--{mock_multipart_body.boundary}'+'\r\nContent-Type: application/octet-stream\r\nContent-Disposition: form-data; name="img"\r\n\r\nHello world\r\n'+f'--{mock_multipart_body.boundary}'+'\r\nContent-Type: application/json\r\nContent-Disposition: form-data; name="test user"\r\n\r\n{"id": "eac79bd3-fd08-4abf-9df2-2565cf3a3845", "workDuration": "2:00:00", "birthDay": "2017-09-04", "startWorkTime": "00:00:00", "createdDateTime": "2022-01-27T12:59:45", "businessPhones": ["+1 412 555 0109"], "mobilePhone": null, "accountEnabled": false, "jobTitle": "Auditor", "manager": {"id": "eac79bd3-fd08-4abf-9df2-2565cf3a3845"}}\r\n'+f'--{mock_multipart_body.boundary}--\r\n'

def test_write_object_value_with_filename(user_1, mock_request_adapter, mock_serialization_writer_factory, mock_multipart_body):
mock_request_adapter.get_serialization_writer_factory = Mock(return_value=mock_serialization_writer_factory)
mock_multipart_body.request_adapter = mock_request_adapter
mock_multipart_body.add_or_replace_part("test user", "application/json", user_1)
mock_multipart_body.add_or_replace_part("file", "application/octet-stream", b"Hello world", "file.txt")

serialization_writer = MultipartSerializationWriter()
serialization_writer.write_object_value("", mock_multipart_body, None)
content = serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == f'--{mock_multipart_body.boundary}'+'\r\nContent-Type: application/json\r\nContent-Disposition: form-data; name="test user"\r\n\r\n{"id": "eac79bd3-fd08-4abf-9df2-2565cf3a3845", "workDuration": "2:00:00", "birthDay": "2017-09-04", "startWorkTime": "00:00:00", "createdDateTime": "2022-01-27T12:59:45", "businessPhones": ["+1 412 555 0109"], "mobilePhone": null, "accountEnabled": false, "jobTitle": "Auditor", "manager": {"id": "eac79bd3-fd08-4abf-9df2-2565cf3a3845"}}\r\n'+f'--{mock_multipart_body.boundary}'+'\r\nContent-Type: application/octet-stream\r\nContent-Disposition: form-data; name="file"; filename="file.txt"\r\n\r\nHello world\r\n'+f'--{mock_multipart_body.boundary}--\r\n'
Loading