[英]SimpleHTTPRequestHandler Override do_GET
I want to extend SimpleHTTPRequestHandler and override the default behavior of do_GET()
. 我想扩展SimpleHTTPRequestHandler并覆盖
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)
. 上面的答案有效但你可能得到
TypeError: a bytes-like object is required, not 'str'
这行的TypeError: a bytes-like object is required, not 'str'
: self.wfile.write(DUMMY_RESPONSE)
。 You need to do this: self.wfile.write(str.encode(DUMMY_RESPONSE))
你需要这样做:
self.wfile.write(str.encode(DUMMY_RESPONSE))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.