Skip to content

Commit b6a806a

Browse files
committed
fix: do not overwrite with empty file if the server returns HTTP 304 when If-None-Match is sent
When `If-None-Match` is sent, the server may return HTTP 304 Not Modified with empty response body. This is problematic, as our code was assuming that there is always a file returned by the server if the HTTP status code < 400
1 parent 16a6dfb commit b6a806a

1 file changed

Lines changed: 13 additions & 2 deletions

File tree

qfieldcloud_sdk/sdk.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,8 +1128,11 @@ def download_file(
11281128
```
11291129
"""
11301130

1131+
headers: dict[str, str] = {}
11311132
if remote_etag and local_filename.exists():
1132-
if calc_etag(str(local_filename)) == remote_etag:
1133+
local_etag = calc_etag(str(local_filename))
1134+
1135+
if local_etag == remote_etag:
11331136
if show_progress:
11341137
print(
11351138
f"{remote_filename}: Already present locally. Download skipped."
@@ -1140,14 +1143,22 @@ def download_file(
11401143
)
11411144
return None
11421145

1146+
headers["If-None-Match"] = local_etag
1147+
11431148
if download_type == FileTransferType.PROJECT:
11441149
url = f"files/{project_id}/{remote_filename}"
11451150
elif download_type == FileTransferType.PACKAGE:
11461151
url = f"packages/{project_id}/latest/files/{remote_filename}"
11471152
else:
11481153
raise NotImplementedError()
11491154

1150-
resp = self._request("GET", url, stream=True)
1155+
resp = self._request("GET", url, stream=True, headers=headers)
1156+
1157+
# Since we are sending the `If-None-Match` header to check the `ETag` of the remote file,
1158+
# we shall expect HTTP 304 in case the local and remote `ETag` match.
1159+
# The early return will prevent overwriting the file with empty contents of the 304 response.
1160+
if resp.status_code == 304:
1161+
return None
11511162

11521163
if not local_filename.parent.exists():
11531164
local_filename.parent.mkdir(parents=True)

0 commit comments

Comments
 (0)