【问题标题】:Sending list of dicts as value of dict with requests.post going wrong将dicts列表作为dict的值发送,requests.post出错
【发布时间】:2016-11-17 17:14:06
【问题描述】:

我有客户端服务器应用程序。 我本地化了麻烦,并有这样的逻辑:

客户:

# -*- 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 dict 时:

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

当然还有其他字段可以很好地与 Django 序列化程序的验证配合使用。但不是那样,因为我有错误的价值观。

【问题讨论】:

  • 那部分也让我很难过。

标签: python django post python-requests oauth2


【解决方案1】:

看起来请求(因为它具有 x-www-encoded-form 默认值)不能包含 dicts 列表作为 dict 中键的值,所以......在这种情况下我应该使用 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

我得到了正确的回应。 解决了!

【讨论】:

  • 此解决方案将不起作用,快速浏览一下 'url_for_working 缺少单引号。
猜你喜欢
  • 2017-05-17
  • 2021-07-25
  • 2020-10-15
  • 2022-06-17
  • 2020-01-08
  • 2013-05-25
  • 2019-01-22
  • 2014-12-17
  • 1970-01-01
相关资源
最近更新 更多