from http.server import HTTPServer, BaseHTTPRequestHandler
from http import HTTPStatus# 导入库
class Handler(BaseHTTPRequestHandler): # 处理用户请求
def do_GET(self): # 修改方法名
self.send_response(200) # 告诉用户接通了
self.send_header("Content_type", 'text/plain;charset=utf-8')
self.end_header()
self.wfile.write("hello,zhis:".encode()+self.path[1:].encode())
if __name__ == '__main__': # 修改变量名
server_address = ('', 9999) # 监听端口
httpd = HTTPServer(server_address, Handler)
httpd.serve_forever() # 让程序运行下去
这段代码是搭建一个服务端,然后通过访问http://localhost:9999在网页显示一段文字,课程效果示例截图
但是在我本地运行一直报错
报错内容:
127.0.0.1 - - [07/Mar/2023 00:20:08] "GET / HTTP/1.1" 200 -
----------------------------------------
Exception occurred during processing of request from ('127.0.0.1', 55961)
Traceback (most recent call last):
File "D:\Python3.9\lib\socketserver.py", line 316, in _handle_request_noblock
self.process_request(request, client_address)
File "D:\Python3.9\lib\socketserver.py", line 347, in process_request
self.finish_request(request, client_address)
File "D:\Python3.9\lib\socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "D:\Python3.9\lib\socketserver.py", line 720, in __init__
self.handle()
File "D:\Python3.9\lib\http\server.py", line 427, in handle
self.handle_one_request()
File "D:\Python3.9\lib\http\server.py", line 415, in handle_one_request
method()
File "D:\20230218\0306\xiugai.py", line 9, in do_GET
self.end_header()
AttributeError: 'Handler' object has no attribute 'end_header'