Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow custom JSONEncoder for the request's json param #2755

Closed
drmaples opened this issue Sep 3, 2015 · 5 comments
Closed

allow custom JSONEncoder for the request's json param #2755

drmaples opened this issue Sep 3, 2015 · 5 comments

Comments

@drmaples
Copy link

drmaples commented Sep 3, 2015

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)
@Lukasa
Copy link
Member

Lukasa commented Sep 3, 2015

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!

@Lukasa Lukasa closed this as completed Sep 3, 2015
@drmaples
Copy link
Author

drmaples commented Sep 3, 2015

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)})

@Lukasa
Copy link
Member

Lukasa commented Sep 3, 2015

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'})

@drmaples
Copy link
Author

drmaples commented Sep 3, 2015

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

@sigmavirus24
Copy link
Contributor

@drmaples then make a function that handles that "globally" for yourself. We won't be introducing this.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Sep 8, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants