简单请求处理程序重写 do_GET
我想要扩展SimpleHTTPRequestHandler这个类,并且重写它默认的do_GET()
方法。我在我的自定义处理器中返回了一个字符串,但客户端却没有收到响应。
这是我的处理器类:
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
我需要做什么更改才能让它正常工作呢?
2 个回答
6
上面的回答是有效的,但你可能会在这一行遇到错误:TypeError: a bytes-like object is required, not 'str'
,意思是需要一个类似字节的对象,而不是字符串。在这种情况下,你需要这样做:self.wfile.write(str.encode(DUMMY_RESPONSE))
。
16
下面是一些类似的(未经测试的代码):
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)