blob: f63f32f87efbe64f76cb85e33e2d2bbf2f523274 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
"""Functions dealing with chunking of files."""
from pathlib import Path
from typing import Iterator
from flask import current_app as app
from werkzeug.utils import secure_filename
from uploader.configutils import uploads_dir
def chunked_binary_read(filepath: Path, chunksize: int = 2048) -> Iterator:
"""Read a file in binary mode in chunks."""
with open(filepath, "rb") as inputfile:
while True:
data = inputfile.read(chunksize)
if data != b"":
yield data
continue
break
def chunk_name(uploadfilename: str, chunkno: int) -> str:
"""Generate chunk name from original filename and chunk number"""
if uploadfilename == "":
raise ValueError("Name cannot be empty!")
if chunkno < 1:
raise ValueError("Chunk number must be greater than zero")
return f"{secure_filename(uploadfilename)}_part_{chunkno:05d}"
def chunks_directory(uniqueidentifier: str) -> Path:
"""Compute the directory where chunks are temporarily stored."""
if uniqueidentifier == "":
raise ValueError("Unique identifier cannot be empty!")
return Path(uploads_dir(app), f"tempdir_{uniqueidentifier}")
|