Search code examples
pythonhttpserverbasehttpserver

How can I access members of the HTTPServer from a BaseHTTPRequestHandler?


I'm putting together a little application that involved both a GUI, HTTP and TCP servers. The GUI controls the responses returned from the HTTP and TCP servers to the clients. I'm using the HTTPServer and SocketServer.TCPServer classes as the servers, with subclasses for both BaseHTTPRequestHandler and StreamRequestHandler. But lets focus on the HTTP side of things for a start.

When the HTTPServer gets a request, it should check the state of the GUI, and respond appropriately. I've added an member variable to the HTTPServer pointing to the GUI, yet cannot figure out a good way to access this field from the BaseHTTPRequestHandler subclass. How can this be done?

Below is the code I currently have, although Python throws an exception, MyHTTPHandler instance has no attribute 'server':

class MyHTTPHandler(BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)
        self._server = server

    def do_GET(self):
        self._server.get_interface().do_something()
        [...]

Solution

  • BaseHTTPRequestHandler has a built in attribute server. Not sure why you are setting another self._server in the inherited class. Would be useful if you can also copy the code in get_interface() method. Also what is this 'server' argument ? instance of inherited HttpServer?