diff --git a/docs/filemanagement.rst b/docs/filemanagement.rst index 3186f38..3ed2a5c 100644 --- a/docs/filemanagement.rst +++ b/docs/filemanagement.rst @@ -254,6 +254,11 @@ Set the content with :meth:`~pydrive2.files.GoogleDriveFile.SetContentFile` or :meth:`~pydrive2.files.GoogleDriveFile.SetContentString`, then call :meth:`~pydrive2.files.GoogleDriveFile.Upload`. +``SetContentFile()`` opens the local file. If ``Upload()`` fails, you can call +``Upload()`` again to retry with the same open file. PyDrive2 closes the file +when the upload succeeds or when you replace its content. If you abandon the +upload after an error, call ``file.content.close()`` to release it immediately. + Sample code continues from `Download file metadata from file ID`_: .. code-block:: python diff --git a/pydrive2/files.py b/pydrive2/files.py index acad9c9..a796a86 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -226,7 +226,8 @@ class GoogleDriveFile(ApiAttributeMixin, ApiResource): Can access and modify metadata like dictionary. """ - content = ApiAttribute("content") + _content = ApiAttribute("content") + _owns_content = ApiAttribute("owns_content") uploaded = ApiAttribute("uploaded") metadata = ApiAttribute("metadata") @@ -275,6 +276,17 @@ def __getitem__(self, key): else: raise FileNotUploadedError() + @property + def content(self): + return self._content + + @content.setter + def content(self, stream): + if self._owns_content and self._content is not stream: + self._content.close() + self._owns_content = False + self._content = stream + def SetContentString(self, content, encoding="utf-8"): """Set content of this file to be a string. @@ -294,10 +306,8 @@ def SetContentString(self, content, encoding="utf-8"): self["mimeType"] = "text/plain" def SetContentFile(self, filename): - """Set content of this file from a file. + """Open a local file for upload. - Opens the file specified by this method. - Will be read, uploaded, and closed by Upload() method. Sets metadata 'name' and 'mimeType' automatically if not specified and the file is uploaded for the first time (id is not set). @@ -305,6 +315,7 @@ def SetContentFile(self, filename): :type filename: str. """ self.content = open(filename, "rb") # noqa: SIM115 - retained for upload + self._owns_content = True if self.get("id") is None: if self.get("name") is None: self["name"] = os.path.basename(filename) @@ -537,8 +548,9 @@ def Upload(self, param=None, *, media_mime_type=None): destination_type = ( metadata.get("mimeType") or self.get("mimeType") or "" ) - if self.dirty["content"] and destination_type.startswith( - "application/vnd.google-apps." + if self._owns_content or ( + self.dirty["content"] + and destination_type.startswith("application/vnd.google-apps.") ): self.content = None self.uploaded = True diff --git a/pydrive2/test/test_file.py b/pydrive2/test/test_file.py index 3e9fa43..1d2c086 100644 --- a/pydrive2/test/test_file.py +++ b/pydrive2/test/test_file.py @@ -851,8 +851,7 @@ def upload_test_document(self): {"mimeType": "application/vnd.google-apps.document"} ) file.SetContentFile(source) - with file.content: - pydrive_retry(file.Upload, media_mime_type="text/plain") + pydrive_retry(file.Upload, media_mime_type="text/plain") self.addCleanup(pydrive_retry, file.Delete) return file, test_util.StripNewlines(content) diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index 1577bec..5e4b9ea 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -1,7 +1,9 @@ import gc +import io import json import weakref from codecs import BOM_UTF8 +from copy import copy from urllib.parse import urlsplit import pytest @@ -447,3 +449,118 @@ def check_request(uri, method, **kwargs): dest = tmp_path / "download" drive.CreateFile({"id": "file"}).GetContentFile(dest, chunksize=2) assert dest.read_bytes() == b"abcd" + + +@pytest.mark.parametrize("existing", [False, True], ids=["create", "update"]) +def test_uploading_a_local_file_takes_two_requests( + mock_drive, tmp_path, existing +): + source = tmp_path / "source" + source.write_bytes(b"payload") + drive, requests = mock_drive( + ({"status": "200", "location": "https://example.test/session"}, ""), + response({"id": "file"}), + ) + file = drive.CreateFile({"id": "file"} if existing else {}) + file.SetContentFile(source) + opened = file.content + assert not requests + file.Upload() + assert opened.closed + start, body = requests + assert start[1] == ("PATCH" if existing else "POST") + path = "/upload/drive/v3/files" + ("/file" if existing else "") + assert urlsplit(start[0]).path == path + assert body[:2] == ("https://example.test/session", "PUT") + + +@pytest.mark.parametrize("fail_on_put", [False, True], ids=["session", "body"]) +def test_failed_upload_keeps_the_file_open_until_retry_succeeds( + mock_drive, tmp_path, monkeypatch, fail_on_put +): + source = tmp_path / "source" + source.write_bytes(b'{"id":"from-retried-upload"}') + session = ( + {"status": "200", "location": "https://example.test/session"}, + "", + ) + drive, requests = mock_drive( + *([session] if fail_on_put else []), + error_response(503, "backendError"), + session, + ({"status": "200"}, "echo_request_body"), + response({"id": "from-retried-upload"}), + ) + file = drive.CreateFile() + monkeypatch.chdir(tmp_path) + file.SetContentFile("source") + opened = file.content + assert not requests + with pytest.raises(ApiRequestError): + file.Upload() + assert not opened.closed + assert [r[1] for r in requests] == ( + ["POST", "PUT"] if fail_on_put else ["POST"] + ) + monkeypatch.chdir(tmp_path.parent) + before = len(requests) + file.Upload() + assert opened.closed + assert file["id"] == "from-retried-upload" + assert file.content is None + retry, upload = requests[before:] + assert retry[:2] == requests[0][:2] + assert upload[:2] == ("https://example.test/session", "PUT") + source.unlink() + file["name"] = "renamed" + before = len(requests) + file.Upload() + (update,) = requests[before:] + assert update[1] == "PATCH" + assert urlsplit(update[0]).path == "/drive/v3/files/from-retried-upload" + assert json.loads(update[2]) == {"name": "renamed"} + + +def test_set_content_file_follows_directory_symlinks( + mock_drive, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + child = tmp_path / "target" / "child" + child.mkdir(parents=True) + alias = tmp_path / "alias" + try: + alias.symlink_to(child, target_is_directory=True) + except OSError: + pytest.skip("Directory symlinks unavailable") + (child.parent / "source").write_bytes(b"through symlink") + (tmp_path / "source").write_bytes(b"beside symlink") + source = alias.relative_to(tmp_path) / ".." / "source" + drive, _ = mock_drive() + file = drive.CreateFile() + file.SetContentFile(source) + with file.content: + assert file.content.read() == source.read_bytes() + + +def test_replacing_content_on_a_copy_closes_only_the_owned_file( + mock_drive, tmp_path +): + source = tmp_path / "source" + source.write_bytes(b"payload") + drive, requests = mock_drive( + error_response(503, "backendError"), + ({"status": "200", "location": "https://example.test/session"}, ""), + response({"id": "uploaded"}), + ) + file = drive.CreateFile() + file.SetContentFile(source) + owned = file.content + with pytest.raises(ApiRequestError): + file.Upload() + external = io.BytesIO(b"external") + copy(file).content = external + assert owned.closed + file.Upload() + file.SetContentString("replacement") + assert external.getvalue() == b"external" + assert [r[1] for r in requests] == ["POST", "POST", "PUT"]