无框架下Python通过HTTP Requests接收Webhook数据的问题
不用框架接收Webhook JSON数据的实现方法
首先得纠正一个误区:requests库是用来发起HTTP请求的,不是用来接收请求的,所以你用它处理Webhook肯定没效果。
如果不能用Flask这类框架,直接用Python标准库自带的http.server就能实现,下面是具体的代码示例,专门处理Webhook发来的POST请求:
from http.server import BaseHTTPRequestHandler, HTTPServer import json class WebhookHandler(BaseHTTPRequestHandler): def do_POST(self): # 获取请求体的长度 content_length = int(self.headers['Content-Length']) # 读取请求体内容 post_data = self.rfile.read(content_length) # 解析JSON数据为Python字典 try: data = json.loads(post_data.decode('utf-8')) # 提取你需要的键值对 test_value = data.get('test', '默认值') print(f"获取到test的值:{test_value}") # 给Webhook返回成功响应 self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps({"status": "success"}).encode('utf-8')) except json.JSONDecodeError: # 处理JSON解析失败的情况 self.send_response(400) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps({"error": "无效的JSON数据"}).encode('utf-8')) def run(server_class=HTTPServer, handler_class=WebhookHandler, port=8000): server_address = ('', port) httpd = server_class(server_address, handler_class) print(f"服务器启动在端口 {port}") try: httpd.serve_forever() except KeyboardInterrupt: httpd.server_close() print("服务器已关闭") if __name__ == '__main__': run()
运行这段代码后,你的服务器就会在8000端口监听POST请求。当Webhook发送{"test": "test_value"}时,代码会解析出test的值并打印出来,同时返回200响应告诉Webhook请求处理成功。
额外注意:
- 如果Webhook只给特定路径发请求,你可以在
do_POST里通过self.path判断路径,只处理目标路径的请求 - 生产环境建议加上Webhook签名校验,避免接收非法请求,但这个示例足够解决你当前的核心问题
内容的提问来源于stack exchange,提问作者JomaOW
相关产品推荐
相关产品推荐

