From 8a4c067e490c1bf07a8cb87c7fdb8bf9dc418c3c Mon Sep 17 00:00:00 2001 From: michalpokusa <72110769+michalpokusa@users.noreply.github.com> Date: Wed, 7 Feb 2024 06:57:39 +0000 Subject: [PATCH] Fix: AttributeError on CircuitPython --- adafruit_httpserver/server.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/adafruit_httpserver/server.py b/adafruit_httpserver/server.py index f103b2c..ba591c3 100644 --- a/adafruit_httpserver/server.py +++ b/adafruit_httpserver/server.py @@ -15,6 +15,7 @@ pass from errno import EAGAIN, ECONNRESET, ETIMEDOUT +from sys import implementation from time import monotonic, sleep from traceback import print_exception @@ -194,6 +195,12 @@ def serve_forever( except Exception: # pylint: disable=broad-except pass # Ignore exceptions in handler function + def _set_socket_level_to_reuse_address(self) -> None: + # Only for CPython, prevents "Address already in use" error + self._sock.setsockopt( + self._socket_source.SOL_SOCKET, self._socket_source.SO_REUSEADDR, 1 + ) + def start(self, host: str, port: int = 80) -> None: """ Start the HTTP server at the given host and port. Requires calling @@ -210,15 +217,13 @@ def start(self, host: str, port: int = 80) -> None: self._sock = self._socket_source.socket( self._socket_source.AF_INET, self._socket_source.SOCK_STREAM ) - try: - # Only for CPython, prevents "Address already in use" error - self._sock.setsockopt( - self._socket_source.SOL_SOCKET, self._socket_source.SO_REUSEADDR, 1 - ) - finally: - self._sock.bind((host, port)) - self._sock.listen(10) - self._sock.setblocking(False) # Non-blocking socket + + if implementation.name != "circuitpython": + self._set_socket_level_to_reuse_address() + + self._sock.bind((host, port)) + self._sock.listen(10) + self._sock.setblocking(False) # Non-blocking socket if self.debug: _debug_started_server(self)