2016-07-14 97 views
0

我有clien-server應用程序。 我本地化的麻煩,這有邏輯:發送字典列表作爲字典的值與requests.post出錯

客戶:

# -*- 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運作良好。但是,在服務器端我沒有產品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']}> 

的QueryDict的這一部分讓我傷心......

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

當我試圖使Python字典:

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

當然,其他領域也可以很好地與Django序列化器驗證。但不是,因爲我有錯誤的價值。

回答

3

看起來像請求(因爲它具有x-www-encoded-form默認值)不能包括字典的列表作爲鍵的值在字典中,所以...我應該在這種情況下使用json。 最後我做了這個功能:

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 

在那裏我得到了正確的迴應。 解決!

+0

此解決方案無法工作,快速瀏覽一下'http:// url_for_working /缺少結束單引號。 – PrestonDocks

+0

@PrestonDocks修復,謝謝)) –