forked from adafruit/Adafruit_CircuitPython_HTTPServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpserver_templates.py
63 lines (47 loc) · 1.68 KB
/
httpserver_templates.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# SPDX-FileCopyrightText: 2023 Michal Pokusa
#
# SPDX-License-Identifier: Unlicense
import os
import re
import socketpool
import wifi
from adafruit_httpserver import Server, Request, Response, FileResponse
try:
from adafruit_templateengine import render_template
except ImportError as e:
raise ImportError("This example requires adafruit_templateengine library.") from e
pool = socketpool.SocketPool(wifi.radio)
server = Server(pool, "/static", debug=True)
# Create /static directory if it doesn't exist
try:
os.listdir("/static")
except OSError as e:
raise OSError("Please create a /static directory on the CIRCUITPY drive.") from e
def is_file(path: str):
return (os.stat(path.rstrip("/"))[0] & 0b_11110000_00000000) == 0b_10000000_00000000
@server.route("/")
def directory_listing(request: Request):
path = request.query_params.get("path", "").replace("%20", " ")
# Preventing path traversal by removing all ../ from path
path = re.sub(r"\/(\.\.)\/|\/(\.\.)|(\.\.)\/", "/", path).strip("/")
# If path is a file, return it as a file response
if is_file(f"/static/{path}"):
return FileResponse(request, path)
items = sorted(
[
item + ("" if is_file(f"/static/{path}/{item}") else "/")
for item in os.listdir(f"/static/{path}")
],
key=lambda item: not item.endswith("/"),
)
# Otherwise, return a directory listing
return Response(
request,
render_template(
"directory_listing.tpl.html",
context={"path": path, "items": items},
),
content_type="text/html",
)
# Start the server.
server.serve_forever(str(wifi.radio.ipv4_address))