Search code examples
pythondjangopostpython-requestsoauth-2.0

Sending list of dicts as value of dict with requests.post going wrong


I have clien-server app. I localized trouble and there logic of this:

Client:

# -*- coding: utf-8 -*-
import requests


def fixing:
    response = requests.post('http://url_for_auth/', data={'client_id': 'client_id', 
                             'client_secret':'its_secret', 'grant_type': 'password', 
                             'username': 'user', 'password': 'password'})
    f = response.json()
    data = {'coordinate_x': 12.3, 'coordinate_y': 8.4, 'address': u'\u041c, 12', 
            'products': [{'count': 1, 'id': 's123'},{'count': 2, 'id': 's124'}]}
    data.update(f)
    response = requests.post('http://url_for_working/, data=data)
    response.text #There I have an Error about which I will say later

oAuth2 working well. But in server-side I have no products in request.data

<QueryDict: {u'token_type': [u'type_is_ok'], u'access_token': [u'token_is_ok'], 
             u'expires_in': [u'36000'], u'coordinate_y': [u'8.4'], 
             u'coordinate_x': [u'12.3'], u'products': [u'count', u'id', u'count', 
             u'id'], u'address': [u'\u041c, 12'], u'scope': [u'read write'], 
             u'refresh_token': [u'token_is_ok']}>

This part of QueryDict make me sad...

'products': [u'count', u'id', u'count', u'id']

And when I tried to make python dict:

request.data.dict()
... u'products': u'id', ...

And for sure other fields working well with Django serializer's validation. But not that, because there I have wrong values.


Solution

  • Looks like request (because it have x-www-encoded-form default) cant include list of dicts as value for key in dict so... I should use json in this case. Finally I maked this func:

    import requests
    import json
    
    
    def fixing:
        response = requests.post('http://url_for_auth/', data={'client_id': 'client_id', 
                             'client_secret':'its_secret', 'grant_type': 'password', 
                             'username': 'user', 'password': 'password'})
        f = response.json()
        headers = {'authorization': f['token_type'].encode('utf-8')+' '+f['access_token'].encode('utf-8'), 
                   'Content-Type': 'application/json'}
        data = {'coordinate_x': 12.3, 'coordinate_y': 8.4, 'address': u'\u041c, 12', 
            'products': [{'count': 1, 'id': 's123'},{'count': 2, 'id': 's124'}]}
        response = requests.post('http://url_for_working/', data=json.dumps(data), 
                                  headers=headers)
        response.text
    

    There I got right response. Solved!