Skip to content

Commit 17e7424

Browse files
committed
Fix handling of sha sum
1 parent 67849af commit 17e7424

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

flask_pymongo/__init__.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -187,20 +187,10 @@ def get_upload(filename):
187187
response.cache_control.public = True
188188
response.make_conditional(request)
189189

190-
# GridFS does not manage its own hash, so we manage our own using its
191-
# metadata storage, to be used for the etag.
192-
sha1_sum = fileobj.metadata.get("sha1_sum", None)
193-
sha1_update_date = fileobj.metadata.get("sha1_update_date", None)
194-
if sha1_update_date and sha1_update_date != fileobj.upload_date:
195-
sha1_sum = None
196-
if sha1_sum is None:
197-
# Compute the sha1 sum of the file for the etag.
198-
pos = fileobj.tell()
199-
raw_data = fileobj.read()
200-
fileobj.seek(pos)
201-
sha1_sum = hashlib.sha1(raw_data).hexdigest()
202-
fileobj.metadata["sha1_sum"] = sha1_sum
203-
fileobj.metadata["sha1_update_date"] = fileobj.upload_date
190+
# Get or compute the sha1 sum for the etag.
191+
metadata = fileobj.metadata
192+
sha1_sum = metadata and metadata.get("sha1_sum")
193+
sha1_sum = sha1_sum or self._compute_sha(fileobj)
204194
response.set_etag(sha1_sum)
205195

206196
return response
@@ -248,5 +238,19 @@ def save_upload(filename):
248238
db_obj = self.db
249239
assert db_obj is not None, "Please initialize the app before calling save_file!"
250240
storage = GridFS(db_obj, base)
251-
id = storage.put(fileobj, filename=filename, content_type=content_type, **kwargs)
241+
242+
# GridFS does not manage its own hash, so we manage our own using its
243+
# metadata storage, to be used for the etag.
244+
sha1_sum = self._compute_sha(fileobj)
245+
metadata = dict(sha1_sum=sha1_sum)
246+
id = storage.put(
247+
fileobj, filename=filename, content_type=content_type, metadata=metadata, **kwargs
248+
)
252249
return id
250+
251+
def _compute_sha(self, fileobj: Any) -> str:
252+
"""Compute the sha sum of a file object."""
253+
pos = fileobj.tell()
254+
raw_data = fileobj.read()
255+
fileobj.seek(pos)
256+
return hashlib.sha1(raw_data).hexdigest()

0 commit comments

Comments
 (0)