Last active
February 16, 2021 22:04
-
-
Save kissgyorgy/267a4b6faec7ec049aa1e80b8567a082 to your computer and use it in GitHub Desktop.
Python: calculate hash and save file at the same time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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