Skip to content

Commit dbdbacd

Browse files
committed
Added Server.debug for verbose messages during development
1 parent 0607776 commit dbdbacd

16 files changed

+59
-35
lines changed

adafruit_httpserver/server.py

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
pass
1616

1717
from errno import EAGAIN, ECONNRESET, ETIMEDOUT
18+
from traceback import print_exception
1819

1920
from .authentication import Basic, Bearer, require_authentication
2021
from .exceptions import (
@@ -37,12 +38,15 @@ class Server:
3738
host: str = None
3839
port: int = None
3940

40-
def __init__(self, socket_source: Protocol, root_path: str = None) -> None:
41+
def __init__(
42+
self, socket_source: Protocol, root_path: str = None, *, debug: bool = False
43+
) -> None:
4144
"""Create a server, and get it ready to run.
4245
4346
:param socket: An object that is a source of sockets. This could be a `socketpool`
4447
in CircuitPython or the `socket` module in CPython.
4548
:param str root_path: Root directory to serve files from
49+
:param bool debug: Enables debug messages useful during development
4650
"""
4751
self._auths = []
4852
self._buffer = bytearray(1024)
@@ -53,6 +57,8 @@ def __init__(self, socket_source: Protocol, root_path: str = None) -> None:
5357
self.root_path = root_path
5458
self.stopped = False
5559

60+
self.debug = debug
61+
5662
def route(self, path: str, methods: Union[str, List[str]] = GET) -> Callable:
5763
"""
5864
Decorator used to add a route.
@@ -119,8 +125,9 @@ def serve_forever(self, host: str, port: int = 80) -> None:
119125
self.poll()
120126
except KeyboardInterrupt: # Exit on Ctrl-C e.g. during development
121127
return
122-
except: # pylint: disable=bare-except
123-
continue
128+
except Exception as error: # pylint: disable=broad-except
129+
if self.debug:
130+
_debug_exception_in_handler(error)
124131

125132
def start(self, host: str, port: int = 80) -> None:
126133
"""
@@ -142,6 +149,9 @@ def start(self, host: str, port: int = 80) -> None:
142149
self._sock.listen(10)
143150
self._sock.setblocking(False) # Non-blocking socket
144151

152+
if self.debug:
153+
_debug_started_server(self)
154+
145155
def stop(self) -> None:
146156
"""
147157
Stops the server from listening for new connections and closes the socket.
@@ -245,7 +255,7 @@ def _handle_request(self, request: Request, handler: Union[Callable, None]):
245255
# ...request.method is GET or HEAD, try to serve a file from the filesystem.
246256
elif request.method in [GET, HEAD]:
247257
self._serve_file_from_filesystem(request)
248-
# ...
258+
249259
else:
250260
Response(request, status=BAD_REQUEST_400).send()
251261

@@ -276,6 +286,9 @@ def poll(self):
276286
if (request := self._receive_request(conn, client_address)) is None:
277287
return
278288

289+
if self.debug:
290+
_debug_incoming_request(request)
291+
279292
# Find a handler for the route
280293
handler = self.routes.find_handler(_Route(request.path, request.method))
281294

@@ -349,3 +362,24 @@ def socket_timeout(self, value: int) -> None:
349362
self._timeout = value
350363
else:
351364
raise ValueError("Server.socket_timeout must be a positive numeric value.")
365+
366+
367+
def _debug_started_server(server: "Server"):
368+
"""Prints a message when the server starts."""
369+
host, port = server.host, server.port
370+
371+
print(f"Started development server on http://{host}:{port}")
372+
373+
374+
def _debug_incoming_request(request: "Request"):
375+
"""Prints a message when a request is received."""
376+
client_ip = request.client_address[0]
377+
method = request.method
378+
size = len(request.raw_request)
379+
380+
print(f"{client_ip} -- {method} {request.path} {size}")
381+
382+
383+
def _debug_exception_in_handler(error: Exception):
384+
"""Prints a message when an exception is raised in a handler."""
385+
print_exception(error)

docs/examples.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
Simple Test
22
-----------
33

4+
**All examples in this document are using** ``Server`` **in** ``debug`` **mode.**
5+
**This mode is useful for development, but it is not recommended to use it in production.**
6+
47
This is the minimal example of using the library.
58
This example is serving a simple static text message.
69

examples/httpserver_authentication_handlers.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717

1818
pool = socketpool.SocketPool(wifi.radio)
19-
server = Server(pool)
19+
server = Server(pool, debug=True)
2020

2121
# Create a list of available authentication methods.
2222
auths = [
@@ -64,5 +64,4 @@ def require_authentication_or_manually_handle(request: Request):
6464
response.send("Not authenticated - Manually handled")
6565

6666

67-
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
6867
server.serve_forever(str(wifi.radio.ipv4_address))

examples/httpserver_authentication_server.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
]
1616

1717
pool = socketpool.SocketPool(wifi.radio)
18-
server = Server(pool, "/static")
18+
server = Server(pool, "/static", debug=True)
1919
server.require_authentication(auths)
2020

2121

@@ -29,5 +29,4 @@ def implicit_require_authentication(request: Request):
2929
response.send("Authenticated")
3030

3131

32-
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
3332
server.serve_forever(str(wifi.radio.ipv4_address))

examples/httpserver_chunked.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010

1111
pool = socketpool.SocketPool(wifi.radio)
12-
server = Server(pool)
12+
server = Server(pool, debug=True)
1313

1414

1515
@server.route("/chunked")
@@ -26,5 +26,4 @@ def chunked(request: Request):
2626
response.send_chunk("ies")
2727

2828

29-
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
3029
server.serve_forever(str(wifi.radio.ipv4_address))

examples/httpserver_cpu_information.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from adafruit_httpserver import Server, Request, Response
1111

1212
pool = socketpool.SocketPool(wifi.radio)
13-
server = Server(pool)
13+
server = Server(pool, debug=True)
1414

1515

1616
@server.route("/cpu-information")
@@ -29,5 +29,4 @@ def cpu_information_handler(request: Request):
2929
response.send(json.dumps(data))
3030

3131

32-
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
3332
server.serve_forever(str(wifi.radio.ipv4_address))

examples/httpserver_handler_serves_file.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111

1212
pool = socketpool.SocketPool(wifi.radio)
13-
server = Server(pool, "/static")
13+
server = Server(pool, "/static", debug=True)
1414

1515

1616
@server.route("/home")
@@ -23,5 +23,4 @@ def home(request: Request):
2323
response.send_file("home.html", root_path="/www")
2424

2525

26-
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
2726
server.serve_forever(str(wifi.radio.ipv4_address))

examples/httpserver_mdns.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
mdns_server.advertise_service(service_type="_http", protocol="_tcp", port=80)
1515

1616
pool = socketpool.SocketPool(wifi.radio)
17-
server = Server(pool, "/static")
17+
server = Server(pool, "/static", debug=True)
1818

1919

2020
@server.route("/")
@@ -26,5 +26,4 @@ def base(request: Request):
2626
response.send_file("index.html")
2727

2828

29-
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
3029
server.serve_forever(str(wifi.radio.ipv4_address))

examples/httpserver_methods.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010

1111
pool = socketpool.SocketPool(wifi.radio)
12-
server = Server(pool)
12+
server = Server(pool, debug=True)
1313

1414

1515
@server.route("/api", [GET, POST, PUT, DELETE])
@@ -34,5 +34,4 @@ def api(request: Request):
3434
response.send("Object deleted")
3535

3636

37-
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
3837
server.serve_forever(str(wifi.radio.ipv4_address))

examples/httpserver_multiple_servers.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010

1111
pool = socketpool.SocketPool(wifi.radio)
1212

13-
bedroom_server = Server(pool, "/bedroom")
14-
office_server = Server(pool, "/office")
13+
bedroom_server = Server(pool, "/bedroom", debug=True)
14+
office_server = Server(pool, "/office", debug=True)
1515

1616

1717
@bedroom_server.route("/bedroom")
@@ -45,9 +45,6 @@ def home(request: Request):
4545
id_address = str(wifi.radio.ipv4_address)
4646

4747
# Start the servers.
48-
49-
print(f"[bedroom_server] Listening on http://{id_address}:5000")
50-
print(f"[office_server] Listening on http://{id_address}:8000")
5148
bedroom_server.start(id_address, 5000)
5249
office_server.start(id_address, 8000)
5350

0 commit comments

Comments
 (0)