Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleHTTPRequestHandler Override do_GET

Tags:

python

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?

like image 485
AJ. Avatar asked Jun 17 '11 20:06

AJ.


2 Answers

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)
like image 177
Roman Bodnarchuk Avatar answered Nov 10 '22 00:11

Roman Bodnarchuk


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))

like image 6
Wafula Samuel Avatar answered Nov 09 '22 23:11

Wafula Samuel