Skip to content

Instantly share code, notes, and snippets.

@kissgyorgy
Last active February 16, 2021 22:04
Show Gist options
  • Save kissgyorgy/267a4b6faec7ec049aa1e80b8567a082 to your computer and use it in GitHub Desktop.
Save kissgyorgy/267a4b6faec7ec049aa1e80b8567a082 to your computer and use it in GitHub Desktop.
Python: calculate hash and save file at the same time
def _calculate_hash_and_save(uploaded_file, temp_file):
file_hash = hashlib.sha256()
for chunk in uploaded_file.chunks():
file_hash.update(chunk)
temp_file.write(chunk)
return file_hash.hexdigest()
def hash_calculator():
file_hash = hashlib.sha256()
while True:
chunk = yield
if not chunk:
break
file_hash.update(chunk)
yield file_hash.hexdigest()
def file_writer(tempfp):
while True:
chunk = yield
tempfp.write(chunk)
def _calculate_hash_and_save(uploaded_file, temp_file):
hash_coro = hash_calculator()
next(hash_coro)
writer_coro = file_writer(temp_file)
next(writer_coro)
for chunk in uploaded_file.chunks():
hash_coro.send(chunk)
writer_coro.send(chunk)
file_hash = next(hash_coro)
return file_hash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment