beep
beep

Reputation: 1245

TypeError: __init__() missing 3 required positional arguments

I'm building a class to handle HTTP GET requests using http.server, this is what i wrote so far:

class webServerHandler(BaseHTTPRequestHandler):
    __HOST = "localhost"
    __PORT = 8080

    # Custom GET response
    def do_GET(self):
        page_content = self.htmlHandler()
        self.wfile.write(page_content) # Send web page

    # HTML code
    def htmlHandler(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        msg = '''
        <html><head><title>Test</title></head>
        <body><h1><center>Test</center></h1></body>
        </html>
        '''
        return bytes(msg, "UTF-8") # UTF-8 Format

    # Run the server
    def serverStart(self):
        # init HTTP Daemon
        http_daemon = HTTPServer((self.__HOST, self.__PORT), webServerHandler)
        http_daemon.serve_forever()
        print("Info: Server started")

and i execute it with:

server = webServerHandler()
server.serverStart()

When i try to execute it it give me this error:

TypeError: __init__() missing 3 required positional arguments: 'request', 'client_address', and 'server'

What i'm doing wrong?

Upvotes: 1

Views: 8115

Answers (2)

heemayl
heemayl

Reputation: 42107

Let's follow the MRO:

In [351]: http.server.BaseHTTPRequestHandler.__mro__
Out[351]: 
(http.server.BaseHTTPRequestHandler,
 socketserver.StreamRequestHandler,
 socketserver.BaseRequestHandler,
 object)

and the __init__ is defined in socketserver.BaseRequestHandler:

def __init__(self, request, client_address, server):
    self.request = request
    self.client_address = client_address
    self.server = server
    self.setup()
    try:
        self.handle()
    finally:
        self.finish()

As you can see you need to provide the needed 3 positional arguments (request, client_address, server) to instantiate the instance as mentioned in the exception.

Upvotes: 2

Nikolas Stevenson-Molnar
Nikolas Stevenson-Molnar

Reputation: 4710

This error is happening because the BaseHTTPRequestHandler has 3 required arguments, and thus your webServerHandler class, which extends BaseHTTPRequestHandler and doesn't override the constructor also has those same required arguments.

You are calling webServerHandler() with no arguments, when you need to call webServerHandler with request, client_address, and server arguments.

Upvotes: 3

Related Questions