pup-fileserver / main.py
pup-py's picture
pup play
f81d12e
raw
history blame
1.69 kB
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"<a href=/files/{path}{x.path}{'/' if x.folder else ''}>{x.path}</a>",
axis=1,
)
res.loc[-1] = [
f"<a href=/files/{ROOT.parent}/>..</a>",
"",
"",
2,
]
res.sort_values(["folder", "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>
"""