Using the json param when making a request is awesome:
payload = {'blip': 'blaz'}
r = requests.get('http://foo.bar', json=payload)
Using the response property is great as well, especially since you can use a custom json decoder:
r.json(cls=MyCustomDecoder)
It would be nice to allow a param to be passed that could be applied to the dumps of the json value.
payload = {'blip': Decimal(69)}
json_params = {'cls': MyCustomEncoder}
r = requests.get('http://foo.bar', json=payload, json_params=json_params)
I think this is interesting, but generally requests is very averse to adding new keyword arguments to requests.*. I don't think it's valuable enough to justify adding the new argument, I'm afraid. Sorry!
Is there a better way to always use a custom json encoder? This way is brittle and gross and does not even work with stuff in master (fine for 2.7.0).
import json
import functools
from decimal import Decimal
import requests
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return round(float(obj), 2)
return json.JSONEncoder.default(self, obj)
# yuck
requests.models.json_dumps = functools.partial(json.dumps, cls=CustomJSONEncoder)
r = requests.post('http://foo.bar', json={'foo': Decimal(69)})
I think the better way is to manually use it yourself:
r = requests.post('http://foo.bar', data=json.dumps(some_data, cls=CustomJSONEncoder), headers={'Content-Type': 'application/json'})
Yep, I am already doing it that way. Was wanting a way to globally have it use a specific encoder/decoder when messing with json
@drmaples then make a function that handles that "globally" for yourself. We won't be introducing this.
Most helpful comment
I think the better way is to manually use it yourself: