发送字典列表作为带有请求的字典值 [英] Sending list of dicts as value of dict with requests.post going wrong

查看:72
本文介绍了发送字典列表作为带有请求的字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有clien-server应用程序.我定位了麻烦,并对此进行了逻辑处理:

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

客户:

# -*- 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中没有产品

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

QueryDict的这一部分让我难过...

This part of QueryDict make me sad...

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

当我尝试制作python字典时:

And when I tried to make python dict:

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

并确保其他字段与Django序列化程序的验证配合良好.但不是那样,因为那里的值有误.

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

推荐答案

看起来像是请求(因为它具有x-www-encoded-form的默认值),不能将dict列表作为dict中的键值包含在内,所以...我应该在这种情况下,请使用json.最后,我做了这个功能:

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!

这篇关于发送字典列表作为带有请求的字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆