Django - how to bind a JSON object when passing it as a request.post () payload

I have the following code in a Django view:

headers = {'Authorization': "key=AAAA7oE3Mj...",
               'Content-type': 'application/json'}
token  = "dJahuaU2p68:A..."
payload = {"data": {}, "to": user_web_tokens}
url = "https://..."
r = requests.post(url, data=payload, headers=headers)

      

The problem is that the answer ends up with error 400 with the error message:

JSON_PARSING_ERROR: Unexpected character (t) at position 0

If I pass in a string instead of JSON:

payload = {"data": {}, "to": user_web_tokens}

... I am getting a slightly different error:

JSON_PARSING_ERROR: Unexpected character (u) at position 19.

I came across a post that says the json object must be compressed before being passed as a payload. But I don't know how it works in Django. Does it have something with serialization? Help me please!

+3


source to share


1 answer


when you are post

with nested dictionary data json.dumps

will help, or you can directly pass it using a parameter json

.

import json
# ...
r = requests.post(url, data=json.dumps(payload), headers=headers)
# or
r = requests.post(url, json=payload, headers=headers)

      



see the official docs .

+6


source







All Articles