在Python请求中将PUT字典放入字典中 [英] PUT dictionary in dictionary in Python requests

查看:54
本文介绍了在Python请求中将PUT字典放入字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要发送具有以下数据结构的PUT请求:

I want to send a PUT request with the following data structure:

{ body : { version: integer, file_id: string }}

这是客户端代码:

def check_id():
    id = request.form['id']
    res = logic.is_id_valid(id)

    file_uuid = request.form['file_id']
    url = 'http://localhost:8050/firmwares'
    r = requests.put(url = url, data = {'body' : {'version': id, 'file_id': str(file_uuid)}})

这是服务器代码:

api.add_resource(resources.FirmwareNewVerUpload, '/firmwares')

class FirmwareNewVerUpload(rest.Resource):
    def put(self):
        try:
            args = parser.parse_args()
        except:
            print traceback.format_exc()

        print 'data: ', str(args['body']), ' type: ', type(args['body'])

        return

服务器打印:

data:  version  type:  <type 'unicode'>

结果不是我想要的.而不是内部字典,我得到一个名称为一个字典键的字符串.如果我将版本"更改为"ver"

And this result is not what I want. Instead of inner dictionary I got a string with name of one dictionary key. If I change 'version' to 'ver'

    r = requests.put(url = url, data = {'body' : {'ver': id, 'file_id': str(file_uuid)}})

服务器打印

data:  ver  type:  <type 'unicode'>

如何发送带有内部词典的词典?

How to send a dictionary with inner dictionary?

推荐答案

在执行 requests.put 时,使用 json = 代替 data = headers = {'content-type':'application/json'} :

Use json= instead of data= when doing requests.put and headers = {'content-type':'application/json'}:

 r = requests.put(url = url, 
                 json = {'body' : {'version': id, 'file_id': str(file_uuid)}}, 
                 headers = {'content-type':'application/json'})

这篇关于在Python请求中将PUT字典放入字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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