I wrote a certain API wrapper using Python's requests
library.
When it gets a response using requests.get
, it attempts to parse as json and takes the raw content if it doesn't work:
resp = requests.get(url, ...)
try:
resp_content = resp.json()
except ValueError:
resp_content = resp.content
return resp_content
This is correct for my purposes. The problem is how long it takes when the downloaded response is an image file, for example, if it is large, then it takes an extremely long time between entering the try
, and failing the json parse and entering the except
.
(I don't know if it takes super long for the .json()
to error at all, or if once it errors it then takes a while to get into the except
.)
Is there a way to see if resp
is json-parsable without attempting to parse it with .json()
? Something like resp.is_json
, so I can instantly know which branch to take (resp.json()
or resp.content
), instead of waiting 30 seconds (large files can take minutes).