Skip to content

Commit 6a5d142

Browse files
committed
Refactor and added trailing / for directories
1 parent 84794f2 commit 6a5d142

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

examples/httpserver_templates.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,33 +25,35 @@
2525
raise OSError("Please create a /static directory on the CIRCUITPY drive.") from e
2626

2727

28+
def is_file(path: str):
29+
return (os.stat(path.rstrip("/"))[0] & 0b_11110000_00000000) == 0b_10000000_00000000
30+
31+
2832
@server.route("/")
2933
def directory_listing(request: Request):
3034
path = request.query_params.get("path", "").replace("%20", " ")
3135

3236
# Preventing path traversal by removing all ../ from path
3337
path = re.sub(r"\/(\.\.)\/|\/(\.\.)|(\.\.)\/", "/", path).strip("/")
3438

35-
if path:
36-
is_file = (
37-
os.stat(f"/static/{path}")[0] & 0b_11110000_00000000
38-
) == 0b_10000000_00000000
39-
else:
40-
is_file = False
41-
4239
# If path is a file, return it as a file response
43-
if is_file:
40+
if is_file(f"/static/{path}"):
4441
return FileResponse(request, path)
4542

43+
items = sorted(
44+
[
45+
item + ("" if is_file(f"/static/{path}/{item}") else "/")
46+
for item in os.listdir(f"/static/{path}")
47+
],
48+
key=lambda item: not item.endswith("/"),
49+
)
50+
4651
# Otherwise, return a directory listing
4752
return Response(
4853
request,
4954
render_template(
5055
"directory_listing.tpl.html",
51-
context={
52-
"path": path,
53-
"items": os.listdir(f"/static/{path}"),
54-
},
56+
context={"path": path, "items": items},
5557
),
5658
content_type="text/html",
5759
)

0 commit comments

Comments
 (0)