我想将requests Response
对象序列化为JSON,最好是以HAR格式。
import requests
resp = requests.get('http://httpbin.org/get')
har = to_har(resp) # <--- magic
但是我用我的谷歌技能没找到任何在线信息。
似乎所有的数据都存在于Response
对象上,我希望不需要实现整个HAR规范,而是可以重用一些代码/工具。
一个有效的答案可能会提供:
现有库或引用起点(如果目前为止没有针对python
和/或requests
的内容)。
目前我的简单3分钟解决方案(非HAR格式)序列化为Response
对象的样子如下(如果没有其他选择,这可能是一个好的起点):
def resp2dict(resp, _root=True):
d = {
'text': resp.text,
'headers': dict(resp.headers),
'status_code': resp.status_code,
'request': {
'url': resp.request.url,
'method': resp.request.method,
'headers': dict(resp.request.headers),
},
}
if _root:
d['history'] = [resp2dict(h, False) for h in resp.history]
return d
我发布这篇文章是因为我认为不仅仅是我自己在一般情况下无法将Response
对象序列化为JSON格式,而不考虑HAR格式。
resp.json()
感到满意,这可能与HAR是否兼容无关,我不知道。您还可以向resp.json()
返回的dict
添加字段。 - gaFF