python - 在 Python 请求中将字典放入字典

标签 python dictionary python-requests

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

{ 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”

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

服务器打印

data:  ver  type:  <type 'unicode'>

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

最佳答案

在执行 requests.putheaders = {'content-type':' 时使用 json= 而不是 data=应用程序/json'}:

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

关于python - 在 Python 请求中将字典放入字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38752091/

相关文章:

swift - 制作一个 Swift 字典,其中键是 "Type"?

python - 谷歌搜索与 python 请求库

Python:请求模块使用 Gevent 抛出异常

python - 如何使用Python请求模块访问谷歌表格数据

python - 从 pandas 多重索引的子集中获取索引

python - 为列赋值时矛盾的 pandas.DataFrame 行为

python - 如何将此字典转换为元组列表?

python - 如何确定字典中有多少个唯一值?

python - 我应该如何最好地模拟和/或避免 Python 中的枚举?

python - 对 TarInfo 列表进行排序