当前位置: 代码网 > it编程>前端脚本>Python > Python如何实现 HTTP echo 服务器

Python如何实现 HTTP echo 服务器

2025年01月07日 Python 我要评论
一个用来做测试的简单的 http echo 服务器。from http.server import httpserver, basehttprequesthandlerimport jsonclass

一个用来做测试的简单的 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 服务器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com