From a34b4e8033a9b6f3c7b6af4f755f2d19962ff1d6 Mon Sep 17 00:00:00 2001 From: Marc Cataford Date: Sat, 19 Aug 2023 11:05:55 -0400 Subject: [PATCH] perf(backend): avoid double-reading uploaded file streams (#25) * perf(backend): avoid double-reading uploaded file content * docs(backend): document file upload endpoint * refactor(backend): hoist uploaded content read + simplify file write block --- backend/rotini/api/files.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/backend/rotini/api/files.py b/backend/rotini/api/files.py index b78d50f..d7178cc 100644 --- a/backend/rotini/api/files.py +++ b/backend/rotini/api/files.py @@ -20,15 +20,22 @@ def list_files(): return files_use_cases.get_all_file_records() -@router.post("/") -async def upload_file(file: UploadFile): +@router.post("/", status_code=201) +async def upload_file(file: UploadFile) -> files_use_cases.FileRecord: + """ + Receives files uploaded by the user, saving them to disk and + recording their existence in the database. + + 201 { } + + The file was uploaded and registered successfully. + """ + content = await file.read() size = len(content) - await file.seek(0) - dest_path = pathlib.Path(settings.STORAGE_ROOT, file.filename) + with open(dest_path, "wb") as f: - content = await file.read() f.write(content) created_record = files_use_cases.create_file_record(str(dest_path), size)