Skip to content

Commit

Permalink
Change the attachment request to pass a file handle rather than readi…
Browse files Browse the repository at this point in the history
…ng in the bytes
  • Loading branch information
gregtatum committed Dec 10, 2024
1 parent 858b925 commit e5369e0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 23 deletions.
20 changes: 10 additions & 10 deletions src/kinto_http/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -923,20 +923,20 @@ def add_attachment(
permissions=None,
mimetype=None,
):
with open(filepath, "rb") as f:
filecontent = f.read()
filename = os.path.basename(filepath)
if mimetype is None:
mimetype, _ = mimetypes.guess_type(filepath)
multipart = [("attachment", (filename, filecontent, mimetype))]
endpoint = self._get_endpoint("attachment", id=id, bucket=bucket, collection=collection)
resp, _ = self.session.request(
"post",
endpoint,
data=json.dumps(data) if data is not None else None,
permissions=json.dumps(permissions) if permissions is not None else None,
files=multipart,
)

with open(filepath, "rb") as file:
resp, _ = self.session.request(
"post",
endpoint,
data=json.dumps(data) if data is not None else None,
permissions=json.dumps(permissions) if permissions is not None else None,
files=[("attachment", (filename, file, mimetype))],
)

return resp

@retry_timeout
Expand Down
28 changes: 15 additions & 13 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import pytest
from pytest_mock.plugin import MockerFixture
from unittest.mock import patch, mock_open

from kinto_http import (
BearerTokenAuth,
Expand Down Expand Up @@ -1429,20 +1430,21 @@ def test_add_attachment_guesses_mimetype(record_setup: Client, tmp_path):

p = tmp_path / "file.txt"
p.write_text("hello")
client.add_attachment(
id="abc",
bucket="a",
collection="b",
filepath=p,
)
with patch("builtins.open", mock_open(read_data="hello")) as mock_file:
client.add_attachment(
id="abc",
bucket="a",
collection="b",
filepath=p,
)

client.session.request.assert_called_with(
"post",
"/buckets/a/collections/b/records/abc/attachment",
data=None,
permissions=None,
files=[("attachment", ("file.txt", b"hello", "text/plain"))],
)
client.session.request.assert_called_with(
"post",
"/buckets/a/collections/b/records/abc/attachment",
data=None,
permissions=None,
files=[("attachment", ("file.txt", mock_file.return_value, "text/plain"))],
)


def test_get_permissions(client_setup: Client):
Expand Down

0 comments on commit e5369e0

Please sign in to comment.