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

Python中使用http.server.BaseHTTPRequestHandler模拟HTTP请求和响应

发布时间:2024-01-04 18:02:32

在Python中,你可以使用http.server.BaseHTTPRequestHandler模拟HTTP请求和响应。这个模块允许你创建一个简单的HTTP服务器,处理GET和POST请求,并发送相应的响应。

以下是一个基本的示例,展示了如何使用BaseHTTPRequestHandler来创建一个简单的HTTP服务器。

首先,导入必要的模块:

from http.server import BaseHTTPRequestHandler, HTTPServer
import json

然后,定义一个继承自BaseHTTPRequestHandler的类,并重写do_GETdo_POST方法:

class MyHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            response = "<h1>Welcome to my website!</h1>"
            self.wfile.write(response.encode())
            return

        elif self.path == '/about':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            response = "<h2>About Me</h2><p>I am a web developer.</p>"
            self.wfile.write(response.encode())
            return

        else:
            self.send_response(404)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            response = "<h1>404 Not Found</h1>"
            self.wfile.write(response.encode())
            return

    def do_POST(self):
        if self.path == '/api':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            post_data = json.loads(post_data)

            # Process the data
            response_data = {'message': 'Success'}
            response_data = json.dumps(response_data)

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(response_data.encode())
            return

        else:
            self.send_response(404)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            response = "<h1>404 Not Found</h1>"
            self.wfile.write(response.encode())
            return

接下来,创建一个HTTPServer实例,并将请求处理程序指定为MyHTTPRequestHandler类:

def run():
    host = 'localhost'
    port = 8000
    server = HTTPServer((host, port), MyHTTPRequestHandler)
    print(f'Server started on {host}:{port}')
    server.serve_forever()


if __name__ == '__main__':
    run()

现在,启动服务器并在浏览器中打开http://localhost:8000。你应该能够看到一个简单的欢迎页面。

如果你访问http://localhost:8000/about,你将看到一个关于我的简短信息。

除了处理GET请求之外,我们还可以在do_POST方法中处理POST请求。在这个例子中,我们接收POST请求的数据,解析JSON数据,然后返回一个成功的响应。

你可以使用curl命令模拟一个POST请求:

curl -X POST -H "Content-Type: application/json" -d '{"name":"John","age":30}' http://localhost:8000/api

服务器将返回一个JSON响应:{"message":"Success"}

这只是一个简单的示例,你可以根据需要进行修改和扩展。请参考Python官方文档以获取更多关于BaseHTTPRequestHandler的信息和用法。