Skip to content

Commit 67849af

Browse files
committed
Use caching for the etag
1 parent 265a305 commit 67849af

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

flask_pymongo/__init__.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -183,15 +183,26 @@ def get_upload(filename):
183183
response.headers["Content-Disposition"] = f"attachment; filename={filename}"
184184
response.content_length = fileobj.length
185185
response.last_modified = fileobj.upload_date
186-
# Compute the sha1 sum of the file for the etag.
187-
pos = fileobj.tell()
188-
raw_data = fileobj.read()
189-
fileobj.seek(pos)
190-
digest = hashlib.sha1(raw_data).hexdigest()
191-
response.set_etag(digest)
192186
response.cache_control.max_age = cache_for
193187
response.cache_control.public = True
194188
response.make_conditional(request)
189+
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
204+
response.set_etag(sha1_sum)
205+
195206
return response
196207

197208
def save_file(

0 commit comments

Comments
 (0)