from fastapi import FastAPI, Request from fastapi.staticfiles import StaticFiles from fastapi.responses import HTMLResponse from itables import to_html_datatable from pathlib import Path import pandas as pd ROOT = Path("/home/user") app = FastAPI() app.mount(path="/files", app=StaticFiles(directory=ROOT), name="HOME") @app.middleware("http") async def file_system(request: Request, call_next): url = request.url if url.path.endswith("/"): return HTMLResponse( content=files_in_folder(url.path.lstrip("/files")) ) response = await call_next(request) return response def files_in_folder(path: str): """List files to render as file index.""" folder = ROOT / path path_glob = folder.glob("*") res = pd.DataFrame( [ ( f.name, f.stat().st_size, pd.Timestamp(int(f.stat().st_mtime), unit="s"), f.is_dir(), ) for f in path_glob ], columns=["path", "size", "mtime", "is_dir"], ) res["path"] = res.apply( lambda x: f"{x.path}", axis=1, ) parent_path = path.rsplit("/", 1)[0] res.loc[-1] = [ f"..", "", "", 2, ] res.sort_values(["is_dir", "path"], ascending=[False, True], inplace=True) table = to_html_datatable( df=res.drop(columns="is_dir"), classes="display nowrap compact", showIndex=False, paging=False, ) return f"""