欢迎访问宙启技术站
智能推送

使用BaseHTTPRequestHandler处理GET请求的示例代码

发布时间:2023-12-24 07:22:53

以下是一个使用BaseHTTPRequestHandler处理GET请求的示例代码:

from http.server import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):
    
    def do_GET(self):
        # 获取请求路径
        path = self.path
        
        # 设置响应状态码为200
        self.send_response(200)
        
        # 设置响应头部
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        
        # 构造响应内容
        if path == '/':
            response_content = 'Hello, World!'
        elif path == '/about':
            response_content = 'About page'
        else:
            response_content = '404 Not Found'
        
        # 发送响应内容
        self.wfile.write(response_content.encode())

def run():
    host = 'localhost'
    port = 8000
    
    try:
        server = HTTPServer((host, port), MyHandler)
        print('Server started on http://{}:{}'.format(host, port))
        server.serve_forever()
    except KeyboardInterrupt:
        print('Server stopped')
        server.server_close()

if __name__ == '__main__':
    run()

使用该代码后,可以在浏览器中访问http://localhost:8000/来获取Hello, World!的响应内容,访问http://localhost:8000/about来获取About page的响应内容。其他路径则会返回404 Not Found的响应内容。

这个示例代码创建了一个自定义的处理请求的处理程序MyHandler,继承自BaseHTTPRequestHandler。在do_GET方法中,我们可以根据不同的路径来返回不同的响应内容。

run函数中,我们创建了一个HTTPServer对象,并将其绑定到localhost的8000端口上。然后调用serve_forever方法来在循环中接收和处理请求。

使用这个示例代码可以很方便地创建一个简单的HTTP服务器,并根据需要进行自定义处理。