使用Python http.client发起请求时触发AttributeError错误求助
问题排查:HTTP请求AttributeError错误
问题代码
headers = { 'Content-Type': 'application/json;charset=UTF-8', 'Cookie': 'A'} body = { "grant_type": "client_credentials", "client_id": "test client", "client_secret": "client secret", "scope": "read"} conn.request("POST", url, headers, json.dumps(body))
错误信息
[ERROR] 2024-08-20T17:30:28.313Z cadf1225-4977-4fa2-8435-1b6f650d0e55 Canary error: Traceback (most recent call last): File "/var/task/index.py", line 92, in handle_canary response = handler(event, context) File "/opt/python/apiCanaryBlueprint.py", line 77, in handler main() File "/opt/python/apiCanaryBlueprint.py", line 70, in main verify_request(method1, url1, payload1, headers1) File "/opt/python/apiCanaryBlueprint.py", line 27, in verify_request conn.request(method, url, headers=json.dumps(body)) File "/var/lang/lib/python3.9/http/client.py", line 1285, in request self._send_request(method, url, body, headers, encode_chunked) File "/var/lang/lib/python3.9/http/client.py", line 1325, in _send_request for hdr, value in headers.items(): AttributeError: 'str' object has no attribute 'items'
错误原因
错误核心是conn.request()的参数顺序错误。http.client.HTTPConnection.request()的标准参数顺序为:request(method, url, body=None, headers={}, encode_chunked=False)
代码中把headers放到了第三个参数(body参数位),把序列化后的body字符串json.dumps(body)放到了第四个参数(headers参数位)。框架处理时会把这个字符串当作headers字典调用items()方法,而字符串没有该属性,因此抛出AttributeError。
解决方法
方法1:调整参数顺序
调换body和headers的位置,匹配标准参数顺序:
headers = { 'Content-Type': 'application/json;charset=UTF-8', 'Cookie': 'A'} body = { "grant_type": "client_credentials", "client_id": "test client", "client_secret": "client secret", "scope": "read"} conn.request("POST", url, json.dumps(body), headers)
方法2:使用关键字参数(推荐)
通过明确指定参数名,彻底避免参数顺序混淆:
conn.request("POST", url, body=json.dumps(body), headers=headers)
内容的提问来源于stack exchange,提问作者girish
相关产品推荐
相关产品推荐

