一个用来做测试的简单的 http echo 服务器。
from http.server import httpserver, basehttprequesthandler
import json
class echohandler(basehttprequesthandler):
def do_get(self):
# 构造响应数据
response_data = {
'path': self.path,
'method': 'get',
'headers': dict(self.headers),
'query_string': self.path.split('?')[1] if '?' in self.path else ''
}
# 设置响应头
self.send_response(200)
self.send_header('content-type', 'application/json')
self.end_headers()
# 发送响应
self.wfile.write(json.dumps(response_data, indent=2).encode())
def do_post(self):
# 获取请求体长度
content_length = int(self.headers.get('content-length', 0))
# 读取请求体
body = self.rfile.read(content_length).decode()
# 构造响应数据
response_data = {
'path': self.path,
'method': 'post',
'headers': dict(self.headers),
'body': body
}
# 设置响应头
self.send_response(200)
self.send_header('content-type', 'application/json')
self.end_headers()
# 发送响应
self.wfile.write(json.dumps(response_data, indent=2).encode())
def run_server(port=8000):
server_address = ('', port)
httpd = httpserver(server_address, echohandler)
print(f'starting server on port {port}...')
httpd.serve_forever()
if __name__ == '__main__':
run_server()这个 http echo 服务器的特点:
- 支持 get 和 post 请求
- 返回 json 格式的响应
- 对于 get 请求,会返回:
- 请求路径
- 请求方法
- 请求头
- 查询字符串
- 对于 post 请求,额外返回请求体内容
使用方法:
- 运行脚本启动服务器
- 使用浏览器或 curl 访问
http://localhost:8000
测试示例:
# get 请求 curl http://localhost:8000/test?foo=bar # post 请求 curl -x post -d "hello=world" http://localhost:8000/test
到此这篇关于python实现一个简单的 http echo 服务器的文章就介绍到这了,更多相关python http echo 服务器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论