Skip to content

Commit bf467a5

Browse files
author
Karl Fleischmann
committed
Split serve_forever to allow polling in loop.
Add polling example. Fix root_path bug when loading static pages.
1 parent 67c3ac3 commit bf467a5

File tree

2 files changed

+73
-22
lines changed

2 files changed

+73
-22
lines changed

adafruit_httpserver.py

Lines changed: 37 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -302,33 +302,48 @@ def serve_forever(self, host: str, port: int = 80, root: str = "") -> None:
302302
:param int port: port
303303
:param str root: root directory to serve files from
304304
"""
305-
self._sock = self._socket_source.socket(
306-
self._socket_source.AF_INET, self._socket_source.SOCK_STREAM
307-
)
308-
self._sock.bind((host, port))
309-
self._sock.listen(1)
305+
self.start_server(host,port,root)
310306

311307
while True:
312308
try:
313-
conn, _ = self._sock.accept()
309+
self.poll_server()
314310
except OSError:
315311
continue
316-
with conn:
317-
# If reading fails, close connection and retry.
318-
try:
319-
length, _ = conn.recvfrom_into(self._buffer)
320-
except OSError:
321-
continue
322312

323-
request = _HTTPRequest(raw_request=self._buffer[:length])
313+
def start(self, host: str, port: int = 80, root: str = "") -> None:
314+
"""
315+
Start the HTTP server at the given host and port. Requires calling
316+
poll() in a while loop to handle incoming requests.
317+
318+
:param str host: host name or IP address
319+
:param int port: port
320+
:param str root: root directory to serve files from
321+
"""
322+
self.root_path = root
324323

325-
# If a route exists for this request, call it. Otherwise try to serve a file.
326-
route = self.routes.get(request, None)
327-
if route:
328-
response = route(request)
329-
elif request.method == "GET":
330-
response = HTTPResponse(filename=request.path, root=root)
331-
else:
332-
response = HTTPResponse(status=HTTPStatus.INTERNAL_SERVER_ERROR)
324+
self._sock = self._socket_source.socket(self._socket_source.AF_INET, self._socket_source.SOCK_STREAM)
325+
self._sock.bind((host, port))
326+
self._sock.listen(10)
333327

334-
response.send(conn)
328+
def poll(self):
329+
"""
330+
Call this method inside your main event loop to get the server to
331+
check for new incoming client requests. When a request comes in,
332+
the application callable will be invoked.
333+
"""
334+
conn, _ = self._sock.accept()
335+
with conn:
336+
length, remaddr = conn.recvfrom_into(self._buffer)
337+
338+
request = _HTTPRequest(raw_request=self._buffer[:length])
339+
340+
# If a route exists for this request, call it. Otherwise try to serve a file.
341+
route = self.routes.get(request, None)
342+
if route:
343+
response = route(request)
344+
elif request.method == "GET":
345+
response = HTTPResponse(filename=request.path, root=self.root_path)
346+
else:
347+
response = HTTPResponse(status=HTTPStatus.INTERNAL_SERVER_ERROR)
348+
349+
response.send(conn)

examples/httpserve_simplepolling.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# SPDX-FileCopyrightText: 2022 Dan Halbert for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: Unlicense
4+
5+
from secrets import secrets # pylint: disable=no-name-in-module
6+
7+
import socketpool
8+
import wifi
9+
10+
from adafruit_httpserver import HTTPServer, HTTPResponse
11+
12+
ssid = secrets["ssid"]
13+
print("Connecting to", ssid)
14+
wifi.radio.connect(ssid, secrets["password"])
15+
print("Connected to", ssid)
16+
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
17+
18+
pool = socketpool.SocketPool(wifi.radio)
19+
server = HTTPServer(pool)
20+
21+
22+
@server.route("/")
23+
def base(request): # pylint: disable=unused-argument
24+
"""Default reponse is /index.html"""
25+
return HTTPResponse(filename="/index.html")
26+
27+
28+
# startup the server
29+
server.start(str(wifi.radio.ipv4_address))
30+
31+
while True:
32+
try:
33+
# processing any waiting requests
34+
server.poll()
35+
except OSError:
36+
continue

0 commit comments

Comments
 (0)