I want to serialize a requests Response
object as json, preferably in HAR format.
import requests
resp = requests.get('http://httpbin.org/get')
har = to_har(resp) # <--- magic
but couldnt find anything online with my google-fu powers.
it seems that all data exist on the Response
object, i hope i dont need to implement the whole HAR spec and there exist some code/utility i can reuse.
a valid answer might give:
existing library or refer to a starting point if nothing exists so far for python
and/or requests
.
currently my simpler 3min solution (not HAR format) serialization to Response
object looks like this (might be good start point if nothing exists):
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
i post this as i think not only me struggle to serialize Response
objects to json in general regardless of HAR format.
resp.json()
, which may or may not comply with HAR, I don't know. You could also add fields to thedict
returned byresp.json()
. – Engeddi