From 67527ef585d7126980397c35fad7179213d8f074 Mon Sep 17 00:00:00 2001 From: boyska Date: Sat, 7 Dec 2024 19:40:03 +0100 Subject: [PATCH] normalize filename --- caricari/private.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/caricari/private.py b/caricari/private.py index eb96357..c7a2997 100644 --- a/caricari/private.py +++ b/caricari/private.py @@ -52,6 +52,18 @@ class UploadModel(BaseModel): file: UploadFile +def normalize_filename(filename: str): + """ + >>> normalize_filename("ciao") + 'ciao' + >>> normalize_filename("Hello, 42 worlds!") + 'Hello42worlds' + """ + return "".join( + c for c in filename + if c.isalnum() or c in '-_' + ) + @app.post("/upload") async def upload( data: Annotated[UploadModel, Form()], @@ -66,7 +78,7 @@ async def upload( # XXX: normalize filename # XXX: avoid duplicates temp = tempfile.NamedTemporaryFile( - prefix=Path(data.file.filename).stem, + prefix=normalize_filename(Path(data.file.filename).stem), suffix=Path(data.file.filename).suffix, dir=Path(CONFIG["general"]["files"]) / directory, delete=False,