用Python新建一个支持指定响应内容http服务器程序
时间: 2023-03-20 21:03:47 浏览: 62
以下是使用 Python 3.x 和标准库中的 http.server 模块编写的简单示例程序,它可以支持指定响应内容的 HTTP 服务器。
```python
import http.server
import socketserver
class MyHandler(http.server.BaseHTTPRequestHandler):
# 定义一个字典,用于存储不同 URL 对应的响应内容
responses = {
"/hello": "Hello, world!",
"/bye": "Goodbye, world!",
"/python": "Python is awesome!",
}
def do_GET(self):
# 获取客户端请求的 URL
url = self.path
# 如果 URL 对应的响应内容存在,则返回该响应内容
if url in self.responses:
self.send_response(200)
self.send_header("Content-type", "text/plain; charset=utf-8")
self.end_headers()
self.wfile.write(self.responses[url].encode("utf-8"))
# 否则返回 404 Not Found
else:
self.send_error(404, "File not found")
PORT = 8080
# 使用 with 语句确保服务器运行完毕后自动关闭
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
print(f"Serving at port {PORT}")
httpd.serve_forever()
```
运行该程序后,可以在浏览器中访问 http://localhost:8080/hello、http://localhost:8080/bye、http://localhost:8080/python 等 URL,即可看到对应的响应内容。可以根据需要自定义 responses 字典中的 URL 和响应内容。