调试代码的时候发现了一个错误
Object of type ‘CaseInsensitiveDict‘ is not JSON serializable
研究后发现requests对请求headers
和body
做了类型准换:
- headers:你用
resp.request.body
访问headers的值的类型,他会是CaseInsensitiveDict
类型 - body:如果你的请求
body
的content-type
是application/json
,你用resp.request.body
访问body的值的类型,他会是bytes
类型
resp.request.headers
json.dumps() 用于将字典格式化为 json 字符串,由于resp.request.headers 类型是CaseInsensitiveDict,那么用json.dumps() 直接格式化会报错
CaseInsensitiveDict:大小写不敏感字典
resp.request.headers的数据示例
{
"method": "POST",
"headers": {
"User-Agent": "python-requests/2.25.1",
"Accept-Encoding": "gzip, deflate",
"Accept": "*/*",
"Connection": "keep-alive",
"dbname": "id_5210a4fb-597c-4c33-8712-377c56614d74",
"Content-Type": "application/json",
"Content-Length": "47"
}
}
而json.dumps()只格式化标准字典dict
, 所以需要将CaseInsensitiveDict转为dict:
dict(resp.request.headers)
resp.request.body
json.loads()用于将json字符串格式化为字典,但resp.request.body是byte类型,所以需要转化为标准字符串:
resp.request.body.decode()