Search code examples
python-3.xhttp-headershttpserver

Basic HTTP Server not fully working and not throwing errors


I've started to explore HTTP servers in python and i wanted to do something very simple. The idea is just if a client connects to "my ip"/admin it shows his header on the web page, if not it just uses the default do_GET() function.

My code:

#!/usr/bin/env python3

import http.server
import socketserver

class HttpHandler(http.server.SimpleHTTPRequestHandler):

    def do_GET(self):
        if self.path == "/admin":
            self.wfile.write("This page is for administrators only".encode())
            self.wfile.write(str(self.headers).encode())
        else:
            http.server.SimpleHTTPRequestHandler.do_GET(self)

http_server=socketserver.TCPServer(("",10002),HttpHandler)
http_server.serve_forever()

For some reason i can't see the headers (unless i do a print of the self.headers to show them in the terminal) it isn't even throwing any errors so i'm kinda lost here.

Thanks for the help


Solution

  • Ok so the solution i came up with (for anyone interested or might friend this thread with the same doubts) is this:

    #!/usr/bin/env python3
    
    import http.server
    import socketserver
    
    class HttpHandler(http.server.SimpleHTTPRequestHandler):
    
        def do_GET(self):
            if self.path == "/admin":
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(bytes("<html> <head><title> Testing </title> </head><body><p> This page is only for administrators</p>"+str(self.headers)+"</body>", "UTF-8"))
            else:
                http.server.SimpleHTTPRequestHandler.do_GET(self)
    
    http_server=socketserver.TCPServer(("",10001), HttpHandler)
    http_server.serve_forever()