python assign literal value of a dictionary to key of another dictionary

2024/10/15 8:22:07

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}

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

    file-data=key1file-data=key2file-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"}

The intended HTTP trace should thus ideally look like this:

    POST /sample_URL/ HTTP/1.1Host: sample_host.comAuthorization: Basic XYZ=Cache-Control: no-cacheContent-Type: multipart/form-data; boundary=----UVWXXXX------WebKitFormBoundaryXYZContent-Disposition: form-data; name="file-data"{"key1": "3","key2": "6","key3":"8" }------WebKitFormBoundaryMANZXCContent-Disposition: form-data; name="file"; filename=""Content-Type: ------WebKitFormBoundaryBNM--

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: To provide more clarity, the API definition is this:

    BodyType: multipart/form-dataForm Parametersfile: required (file)The file to be uploadedfile-data: (string)Example:{"key1": "3","key2": "6","key3": "8"} 

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

    #!/usr/bin/env python# -*- coding: utf-8 -*-import requestsurl = "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

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

    send: 'POST sample_url HTTP/1.1Host: abc.comConnection: keep-aliveAccept-Encoding: gzip,deflateAccept: */*python-requests/2.11.1Content-type: multipart/form-dataAuthorization: Basic ABCDXXX=Content-Length: 342--CDXXXXYYYYYContent-Disposition:form-data; name="file-data"{\'key1\': \'3\',\'key2\': \'6\',\'key3\': \'8\'}--88cdLMNO999999Content-Disposition: form-data; name="file";filename="logo.png"\x89PNG\n\r\n--cbCDEXXXNNNN--
Answer

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"})

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}

Whis is not valid python syntax btw.

https://en.xdnf.cn/q/117854.html

Related Q&A

python regex findall span

I wanna find all thing between <span class=""> and </span> p = re.compile(<span class=\"\">(.*?)\</span>, re.IGNORECASE) text = re.findall(p, z)for exampl…

Why cant I view updates to a label while making an HTTP request in Python

I have this code :def on_btn_login_clicked(self, widget):email = self.log_email.get_text()passw = self.log_pass.get_text()self.lbl_status.set_text("Connecting ...")params = urllib.urlencode({…

plotting multiple graph from a csv file and output to a single pdf/svg

I have some csv data in the following format.Ln Dr Tag Lab 0:01 0:02 0:03 0:04 0:05 0:06 0:07 0:08 0:09 L0 St vT 4R 0 0 0 0 0 0…

parallel python: just run function n times [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 9…

how to specify the partition for mapPartition in spark

What I would like to do is compute each list separately so for example if I have 5 list ([1,2,3,4,5,6],[2,3,4,5,6],[3,4,5,6],[4,5,6],[5,6]) and I would like to get the 5 lists without the 6 I would do …

Keeping just the hh:mm:ss from a time delta

I have a column of timedeltas which have the attributes listed here. I want the output in my pandas table to go from:1 day, 13:54:03.0456to:13:54:03How can I drop the date from this output?

How to return the index of numpy ndarray based on search?

I have a numpy 2D array, import numpy as np array1 = array([[ 1, 2, 1, 1],[ 2, 2, 2, 1],[ 1, 1, 1, 1],[1, 3, 1, 1],[1, 1, 1, 1]])I would like to find the element 3 and know its location. So,…

Python:Christmas Tree

I need to print a Christmas tree that looks like this:/\ / \ / \Here is my code so far:for count in range (0,20):variable1 = count-20variable2 = count*2print({0:{width1}}{1:{width2}} .format(/,\\,…

Send back json to client side

I just started developing with cherrypy, so I am struggling a little bit. In client side I am selecting some data, converting it to json and sending to server side via post method. Then I am doing a fe…

Can I use PyInstaller from Python 2.7 to compile an executable for a Python 3 script?

So, I tried installing PyInstaller in my Python 3.4 dir but, for some reason, Ive been getting errors and Im not able to install it. I however, do have a working PyInstaller in my Python 2.7 dir. I nee…