python将字典的文字值分配给另一个字典的键 [英] python assign literal value of a dictionary to key of another dictionary

查看:429
本文介绍了python将字典的文字值分配给另一个字典的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为特定的请求正文形成Web有效负载,但无法正确处理.我需要的是传递我的身体数据,如下所示

I am trying to form a web payload for a particular request body but unable to get it right. What I need is to pass my body data as below

data={'file-data':{"key1": "3","key2": "6","key3": "8"}}

我完整的有效负载请求看起来像这样

My complete payload request looks like this

payload={url,headers, data={'file-data':{"key1": "3","key2": "6","key3": "8"}},files=files}

但是,当我通过此操作时,python会尝试解析每个单独的键值,并像这样将其分配给文件数据"键

However, when I pass this, python tries to parse each individual key value and assigns to the 'file-data' key like this

    file-data=key1
    file-data=key2
    file-data=key3

,依此类推,对于我在嵌套字典中传递的尽可能多的键而言.但是,要求是将整个字典作为这样的文字内容传递((不按每个键拆分值):

and so on for as many keys I pass within the nested dictionary. The requirement however, is to pass the entire dictionary as a literal content like this(without splitting the values by each key):

    file-data={"key1": "3","key2": "6","key3": "8"}

因此,理想的HTTP跟踪在理想情况下应如下所示:

The intended HTTP trace should thus ideally look like this:

    POST /sample_URL/ HTTP/1.1
    Host: sample_host.com
    Authorization: Basic XYZ=
    Cache-Control: no-cache
    Content-Type: multipart/form-data; boundary=----UVWXXXX

    ------WebKitFormBoundaryXYZ
    Content-Disposition: form-data; name="file-data"

    {"key1": "3","key2": "6","key3":"8" }
    ------WebKitFormBoundaryMANZXC
    Content-Disposition: form-data; name="file"; filename=""
    Content-Type: 


    ------WebKitFormBoundaryBNM--

因此,我想将此作为POST请求(使用python请求库)的有效负载的一部分.任何建议都将受到感激-

As such, I want to use this as part of a payload for a POST request(using python requests library). Any suggestions are appreciated in advance-

Edit1 :为了提供更多的清晰度,API定义是这样的:

Edit1: To provide more clarity, the API definition is this:

    Body
    Type: multipart/form-data
    Form Parameters

    file: required (file)

    The file to be uploaded
    file-data: (string)

    Example:

    {
      "key1": "3",
      "key2": "6",
      "key3": "8"
    } 

我使用的python代码段(检查建议后的 )是这样的:

The python code snippet I used(after checking suggestions) is this:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-

    import requests
    url = "https://sample_url/upload"
    filepath='mypath' 
    filename='logo.png'
    f=open(filepath+'\\'+filename)
    filedata={'file-data':"{'key1': '3','key2': '6','key3': '8'}"}  
    base64string = encodestring('%s:%s' % ('user', 'password').replace('\n', '')
    headers={'Content-type': 'multipart/form-data','Authorization':'Basic %s' % base64string} 


     r = requests.post(url=url,headers=headers,data=filedata,files={'file':f})
     print r.text

我现在得到的错误仍然与下图相同:

The error I get now is still the same as shown below:

     {"statusCode":400,"errorMessages":[{"severity":"ERROR","errorMessage":"An exception has occurred"]

它还说某些条目丢失或不正确.请注意,在二进制模式下打开文件参数后,我也尝试传递文件参数,但它会抛出相同的错误消息

It also says that some entries are either missing or incorrect. Note that I have tried passing the file parameter after opening it in binary mode as well but it throws the same error message

我也通过python打印了HTTP跟踪,它看起来像这样:

I got the HTTP trace printed out via python too and it looks like this:

    send: 'POST sample_url HTTP/1.1
    Host: abc.com
    Connection: keep-alive
    Accept-Encoding: gzip,deflate
    Accept: */*
    python-requests/2.11.1
    Content-type: multipart/form-data
    Authorization: Basic ABCDXXX=
    Content-Length: 342
    --CDXXXXYYYYY
    Content-Disposition:form-data; name="file-data"
    {\'key1\': \'3\',\'key2\': \'6\'
    ,\'key3\': \'8\'}
    --88cdLMNO999999
    Content-Disposition: form-data; name="file";
    filename="logo.png"\x89PNG\n\r\n--cbCDEXXXNNNN--

推荐答案

如果要发布带有Python请求的 JSON ,则应使用data,但json:

If you want to post JSON with python requests, you should NOT use data but json:

r = requests.post('http://httpbin.org/post', json={"key": "value"})

由于您的示例,我只能猜测您正在使用data

I can only guess that you are using data because of your example

payload={url,headers, data={'file-data':{"key1": "3","key2": "6","key3": "8"}},files=files}

这不是有效的python语法.

Whis is not valid python syntax btw.

这篇关于python将字典的文字值分配给另一个字典的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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