0

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()
Rodalm
  • 5,169
  • 5
  • 21
  • You're importing a class HTTPServer from the http.server modeule, and then you're defining a new class with the same name. So, you're going to have http.server.HTTPServer objects, and MyServer.HTTPServer objects. – Ignatius Reilly Jun 18 '22 at 21:46
  • Does this answer your question? [Is there a benefit to defining a class inside another class in Python?](https://stackoverflow.com/questions/78799/is-there-a-benefit-to-defining-a-class-inside-another-class-in-python), in particular https://stackoverflow.com/a/49812827/15032126 – Ignatius Reilly Jun 18 '22 at 21:49

0 Answers0