Overriding SimpleHTTPRequestHandler do_GET

I want to extend SimpleHTTPRequestHandler and override the default behavior do_GET(). I am returning a string from my custom handler, but the client does not receive a response.

Here is my handler class:

DUMMY_RESPONSE = """Content-type: text/html

<html>
<head>
<title>Python Test</title>
</head>

<body>
Test page...success.
</body>
</html>
"""

class MyHandler(CGIHTTPRequestHandler):

    def __init__(self,req,client_addr,server):
        CGIHTTPRequestHandler.__init__(self,req,client_addr,server)

    def do_GET(self):
        return DUMMY_RESPONSE

What should I change to make this work right?

+3
source share
2 answers

Something like (unverified code):

def do_GET(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.send_header("Content-length", len(DUMMY_RESPONSE))
    self.end_headers()
    self.wfile.write(DUMMY_RESPONSE)
+9
source

The above answer works, but you can get TypeError: a bytes-like object is required, not 'str'in this line: self.wfile.write(DUMMY_RESPONSE). You need to do this:self.wfile.write(str.encode(DUMMY_RESPONSE))

0
source

All Articles