Spaces:
Runtime error
Runtime error
| 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") | |
| 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 | |
| folder_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 folder_glob | |
| ], | |
| columns=["path", "size", "mtime", "is_dir"], | |
| ) | |
| res["path"] = res.apply( | |
| lambda x: f"<a href=/files/{path}{x.path}{'/' if x.is_dir else ''}>{x.path}</a>", | |
| axis=1, | |
| ) | |
| if folder != ROOT: # create ".." unless in ROOT | |
| if "/" in path[:-1]: | |
| parent_path = path.rsplit("/", 2)[0] | |
| parent_url = f"/files/{parent_path}/" | |
| else: | |
| parent_url = "/" | |
| res.loc[-1] = [f"<a href={parent_url}>..</a>", "", "", 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""" | |
| <div style="width:50%; margin: 0 auto;"> | |
| <h1>{folder}</h1><br> | |
| {table} | |
| </div> | |
| """ | |