Python2升级Python3后webhook POST请求报str类型TypeError如何解决
问题解决方法
报错根因
你遇到的TypeError: POST data should be bytes...报错有两个核心原因:
- 升级后的Python3代码存在缩进错误,
send_webhook_request函数内部所有逻辑都没有正确缩进,导致body = body.encode()转换逻辑根本没有执行,传入的json.dumps()生成的字符串直接传给了urllib.request.Request,触发类型校验错误 - 编码转换未显式指定编码格式,存在跨环境兼容性隐患
修复步骤
- 先修正函数缩进,确保所有函数内代码都在函数定义的缩进层级下
- 显式指定编码格式转换body为字节类型,还可以增加类型判断避免重复编码报错
- 可选优化返回值格式,根据业务需要把响应的字节类型转为字符串
修正后完整代码
import sys import base64 import urllib.error import urllib.request def send_webhook_request(url, body, user_agent=None): if url is None: print("ERROR No URL provided", file=sys.stderr) return False print("INFO Sending POST request to url=%s with size=%d bytes payload" % (url, len(body)), file=sys.stderr) print("DEBUG Body: %s" % body, file=sys.stderr) try: user="integration.argossplunk" password="hv6ep_gXR+M$#8tk@e4cePYx@*Er4VD#" credentials = (user + ':' + password).encode('utf-8') base64_encoded_credentials = base64.b64encode(credentials).decode('utf-8') headers = {'Authorization': 'Basic ' + base64_encoded_credentials, "Content-Type": "application/json", 'User-Agent': user_agent} # 新增类型判断+显式指定utf-8编码,避免报错 if isinstance(body, str): body = body.encode('utf-8') req = urllib.request.Request(url, body, headers) res = urllib.request.urlopen(req) response = res.read() if 200 <= res.code < 300: print("INFO Webhook receiver responded with HTTP status=%d" % res.code, file=sys.stderr) # 如果需要返回字符串可以改为 return response.decode('utf-8') return response else: print("ERROR Webhook receiver responded with HTTP status=%d" % res.code, file=sys.stderr) return False except urllib.error.HTTPError as e: print("ERROR Error sending webhook request: %s" % e, file=sys.stderr) except urllib.error.URLError as e: print("ERROR Error sending webhook request: %s" % e, file=sys.stderr) except ValueError as e: print("ERROR Invalid URL: %s" % e, file=sys.stderr) return False
修复后原来的调用方式send_webhook_request(url, json.dumps(body), user_agent=user_agent)可以正常运行。
内容的提问来源于stack exchange,提问作者umang kaul
相关产品推荐
相关产品推荐

