From 079d9909c0ce233a3375e20869c795b7812afc29 Mon Sep 17 00:00:00 2001 From: s3lph Date: Sun, 8 Jul 2018 15:10:22 +0200 Subject: [PATCH] Some typing fixes that make mypy a litte happier --- matemat/webserver/httpd.py | 28 +++++++++++++++++++++------- matemat/webserver/requestargs.py | 2 +- matemat/webserver/util.py | 4 ++-- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/matemat/webserver/httpd.py b/matemat/webserver/httpd.py index b703f72..3215ad2 100644 --- a/matemat/webserver/httpd.py +++ b/matemat/webserver/httpd.py @@ -1,5 +1,5 @@ -from typing import Any, Callable, Dict, Optional, Tuple, Union +from typing import Any, Callable, Dict, Optional, Tuple, Type, Union import traceback @@ -34,7 +34,7 @@ _PAGELET_PATHS: Dict[str, Callable[[str, # HTTP method (GET, POST, ...) RequestArguments, # HTTP Request arguments Dict[str, Any], # Session vars Dict[str, str]], # Response headers - Tuple[int, Union[bytes, str]]]] = dict() # Returns: (status code, response body) + Tuple[int, Optional[Union[bytes, str]]]]] = dict() # Returns: (status code, response body) # Inactivity timeout for client sessions @@ -82,6 +82,23 @@ def pagelet(path: str): return http_handler +class MatematHTTPServer(HTTPServer): + """ + A http.server.HTTPServer subclass that acts as a container for data that must be persistent between requests. + """ + + def __init__(self, + server_address: Any, + handler: Type[BaseHTTPRequestHandler], + webroot: str, + bind_and_activate: bool = True) -> None: + super().__init__(server_address, handler, bind_and_activate) + # Resolve webroot directory + self.webroot = os.path.abspath(webroot) + # Set up session vars dict + self.session_vars: Dict[str, Tuple[datetime, Dict[str, Any]]] = dict() + + class MatematWebserver(object): """ Then main webserver class, internally uses Python's http.server. @@ -113,11 +130,7 @@ class MatematWebserver(object): # Rewrite IPv4 address to IPv6-mapped form listen = f'::ffff:{listen}' # Create the http server - self._httpd = HTTPServer((listen, port), HttpHandler) - # Set up session vars dict - self._httpd.session_vars: Dict[str, Tuple[datetime, Dict[str, Any]]] = dict() - # Resolve webroot directory - self._httpd.webroot = os.path.abspath(webroot) + self._httpd = MatematHTTPServer((listen, port), HttpHandler, webroot) def start(self) -> None: """ @@ -136,6 +149,7 @@ class HttpHandler(BaseHTTPRequestHandler): def __init__(self, request: bytes, client_address: Tuple[str, int], server: HTTPServer) -> None: super().__init__(request, client_address, server) + self.server: MatematHTTPServer @property def server_version(self) -> str: diff --git a/matemat/webserver/requestargs.py b/matemat/webserver/requestargs.py index 2150b31..373db90 100644 --- a/matemat/webserver/requestargs.py +++ b/matemat/webserver/requestargs.py @@ -50,7 +50,7 @@ class RequestArguments(object): """ return _View.of(self.__container[key]) - def __iter__(self) -> Iterator['RequestArguments']: + def __iter__(self) -> Iterator['RequestArgument']: """ Returns an iterator over the values in this instance. Values are represented as immutable views. diff --git a/matemat/webserver/util.py b/matemat/webserver/util.py index 6e19d7b..c95d303 100644 --- a/matemat/webserver/util.py +++ b/matemat/webserver/util.py @@ -97,7 +97,7 @@ def parse_args(request: str, postbody: Optional[bytes] = None, enctype: str = 't tokens = urllib.parse.urlparse(request) # Parse the GET arguments if len(tokens.query) == 0: - getargs = dict() + getargs: Dict[str, List[str]] = dict() else: getargs = urllib.parse.parse_qs(tokens.query, strict_parsing=True, keep_blank_values=True, errors='strict') @@ -112,7 +112,7 @@ def parse_args(request: str, postbody: Optional[bytes] = None, enctype: str = 't # Parse the POST body pb: str = postbody.decode('utf-8') if len(pb) == 0: - postargs = dict() + postargs: Dict[str, List[str]] = dict() else: postargs = urllib.parse.parse_qs(pb, strict_parsing=True, keep_blank_values=True, errors='strict') # Write all POST values into the dict, overriding potential duplicates from GET