1
0
Fork 0
forked from s3lph/matemat

Some typing fixes that make mypy a litte happier

This commit is contained in:
s3lph 2018-07-08 15:10:22 +02:00
parent 528f7322ac
commit 079d9909c0
3 changed files with 24 additions and 10 deletions

View file

@ -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 import traceback
@ -34,7 +34,7 @@ _PAGELET_PATHS: Dict[str, Callable[[str, # HTTP method (GET, POST, ...)
RequestArguments, # HTTP Request arguments RequestArguments, # HTTP Request arguments
Dict[str, Any], # Session vars Dict[str, Any], # Session vars
Dict[str, str]], # Response headers 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 # Inactivity timeout for client sessions
@ -82,6 +82,23 @@ def pagelet(path: str):
return http_handler 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): class MatematWebserver(object):
""" """
Then main webserver class, internally uses Python's http.server. Then main webserver class, internally uses Python's http.server.
@ -113,11 +130,7 @@ class MatematWebserver(object):
# Rewrite IPv4 address to IPv6-mapped form # Rewrite IPv4 address to IPv6-mapped form
listen = f'::ffff:{listen}' listen = f'::ffff:{listen}'
# Create the http server # Create the http server
self._httpd = HTTPServer((listen, port), HttpHandler) self._httpd = MatematHTTPServer((listen, port), HttpHandler, webroot)
# 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)
def start(self) -> None: def start(self) -> None:
""" """
@ -136,6 +149,7 @@ class HttpHandler(BaseHTTPRequestHandler):
def __init__(self, request: bytes, client_address: Tuple[str, int], server: HTTPServer) -> None: def __init__(self, request: bytes, client_address: Tuple[str, int], server: HTTPServer) -> None:
super().__init__(request, client_address, server) super().__init__(request, client_address, server)
self.server: MatematHTTPServer
@property @property
def server_version(self) -> str: def server_version(self) -> str:

View file

@ -50,7 +50,7 @@ class RequestArguments(object):
""" """
return _View.of(self.__container[key]) 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. Returns an iterator over the values in this instance. Values are represented as immutable views.

View file

@ -97,7 +97,7 @@ def parse_args(request: str, postbody: Optional[bytes] = None, enctype: str = 't
tokens = urllib.parse.urlparse(request) tokens = urllib.parse.urlparse(request)
# Parse the GET arguments # Parse the GET arguments
if len(tokens.query) == 0: if len(tokens.query) == 0:
getargs = dict() getargs: Dict[str, List[str]] = dict()
else: else:
getargs = urllib.parse.parse_qs(tokens.query, strict_parsing=True, keep_blank_values=True, errors='strict') 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 # Parse the POST body
pb: str = postbody.decode('utf-8') pb: str = postbody.decode('utf-8')
if len(pb) == 0: if len(pb) == 0:
postargs = dict() postargs: Dict[str, List[str]] = dict()
else: else:
postargs = urllib.parse.parse_qs(pb, strict_parsing=True, keep_blank_values=True, errors='strict') 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 # Write all POST values into the dict, overriding potential duplicates from GET