I have a problem that I cannot describe well, but I'll try. I'm trying to create my http server with own protocol used to process commands in get requests.
But I need somehow pass used protocol to class HttpServer
from MyServer
, which is only referenced as argument of class initializer of ThreadingSimpleServer
. But it is only passed as class reference.
Right now, my question is, how should I extend the initializer of HttpServer
to take the protocol class argument, and how to pass this argument through ThreadingSimpleServer
initializer to make it work.
import socketserver
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import threading
class Protocol():
def processGetReq(self):
pass
class MyServer():
def __init__(self, protocol: Protocol, srvr_ip="127.0.0.1", srvr_port=10001):
self.srvr_addr = (srvr_ip, srvr_port)
self.protocol = protocol
def start(self):
self.server = self.ThreadingSimpleServer(self.srvr_addr, RequestHandlerClass=self.HttpServer)
self._server_thread = threading.Thread(target=self._handle_requests)
self._server_thread.start()
def _handle_requests(self):
while 1:
self.server.handle_request()
def serveForever(self):
self._server_thread.join()
class HttpServer(BaseHTTPRequestHandler):
def __init__(self, request: bytes, client_address: tuple[str, int], server: socketserver.BaseServer) -> None:
super().__init__(request, client_address, server)
def do_GET(self):
self.protocol.processGetReq()
self._set_headers()
self.wfile.write(b"OK, get")
class ThreadingSimpleServer(socketserver.ThreadingMixIn, HTTPServer):
pass
##################################################################
##################### START ######################
##################################################################
server = MyServer(SomeProtocol()) # Here would be some protocol subclass of baseclass Protocol
server.start()
print("Server ready!")
server.serveForever()