X-Git-Url: https://git.mdrn.pl/wolnelektury.git/blobdiff_plain/5c14b2f1216cf266efd63f4de84e3f83bb99c9ff..fc8859ef3e192b8e125462ff2cbda0e5dfff3d5d:/src/catalogue/utils.py?ds=sidebyside diff --git a/src/catalogue/utils.py b/src/catalogue/utils.py index ee3631c76..e6e567b8f 100644 --- a/src/catalogue/utils.py +++ b/src/catalogue/utils.py @@ -1,5 +1,5 @@ -# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. -# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. +# This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later. +# Copyright © Fundacja Wolne Lektury. See NOTICE for more information. # import hashlib import os.path @@ -334,3 +334,20 @@ def set_file_permissions(self, fieldfile): if fieldfile.instance.preview: fieldfile.set_readable(False) + +CHUNK_SIZE = 1024 * 1024 # 1 MB + +def iter_file(field_file, chunk_size=CHUNK_SIZE): + storage = field_file.storage + if hasattr(storage, "bucket"): + # If through S3Storage, chunk directly from + # boto interface to avoid loading the whole thing. + key = storage._normalize_name(field_file.name) + body = storage.bucket.Object(key).get()["Body"] + try: + yield from body.iter_chunks(chunk_size) + finally: + body.close() + else: + with field_file.open("rb") as f: + yield from f.chunks(chunk_size)