@@ -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 )
0 commit comments