I want to extend SimpleHTTPRequestHandler and override the default behavior of do_GET()
. I am returning a string from my custom handler but the client doesn't receive the 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 must I change to make this work correctly?
Something like (untested 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)
The above answer works but you might get TypeError: a bytes-like object is required, not 'str'
on this line: self.wfile.write(DUMMY_RESPONSE)
.
You need to do this: self.wfile.write(str.encode(DUMMY_RESPONSE))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With