Shm*_*ikA 6 python serialization python-3.x python-requests har
我想将请求 Response对象序列化为json,最好是HAR格式。
import requests
resp = requests.get('http://httpbin.org/get')
har = to_har(resp) # <--- magic
Run Code Online (Sandbox Code Playgroud)
但是用我的Google Fu功能在网上找不到任何东西。
似乎所有数据都存在于该Response对象上,我希望我不需要实现整个HAR规范,并且存在一些可以重用的代码/实用程序。
一个有效的答案可能是:现有的库,或者如果python和和/或到目前为止都不存在,请参考起点requests。
当前,我对Response对象的3min解决方案(不是HAR格式)更简单的序列化看起来像这样(如果不存在,可能是一个很好的起点):
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
Run Code Online (Sandbox Code Playgroud)
我之所以发表此文章,是因为我认为Response,无论HAR格式如何,我不仅会努力将对象序列化为json。
小智 2
目前我更简单的 3 分钟解决方案(不是 HAR 格式)序列化到 Response 对象看起来像这样(如果什么都不存在,可能是一个很好的起点):
看起来这是最好的解决方案。我已经检查了 PyPI 上的每个与 HAR 相关的库,我发现的唯一接近的解决方案(除了har2requests)是marshmallow-har。不幸的是,marshmallow_har.Response.__schema__内部结构既不匹配requests.Response也不匹配urllib3.response.HTTPResponse。所以,我看到的解决方案是:
marshmallow-har即可使用。attribute通过向字段提供参数来创建您自己的棉花糖模式。我建议分叉和扩展marshmallow-har,但它使用工厂和其他奇怪的魔法,并且不能轻易扩展。所以,最好从零开始。并考虑开源您的解决方案:)
| 归档时间: |
|
| 查看次数: |
259 次 |
| 最近记录: |