@@ -187,20 +187,10 @@ def get_upload(filename):
187
187
response .cache_control .public = True
188
188
response .make_conditional (request )
189
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
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 )
204
194
response .set_etag (sha1_sum )
205
195
206
196
return response
@@ -248,5 +238,19 @@ def save_upload(filename):
248
238
db_obj = self .db
249
239
assert db_obj is not None , "Please initialize the app before calling save_file!"
250
240
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
+ )
252
249
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