Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

Send post request with multiple data files and strings in python script

Im trying to send a post request I need to upload 2 files and some other strings and integers, what is the best way to do this from inside a python script?

I can use curl in the bash terminal and it works but not sure how to format it for a python script?

There are multiple variables that have been defined earlier in the script

os.system(r"curl -F ''file=@./'+  t + '.files/' + t + '.png'' -F ''info=@./' +  t + '.files/info.txt'' -F ''name=' + name' -F ''description=' + description' -F ''type=' + reso' -F 'source=' + source' -F 'live=' + live' + url + API")

variables are t, name, description, reso, source, live, URL and API

how do I send a post request in python? I came across answers that suggest importing requests but if my file path has a variable in it what syntax would I use?

question from:https://stackoverflow.com/questions/65952846/send-post-request-with-multiple-data-files-and-strings-in-python-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the most ideal way would be this:

import requests

url = "{YOUR URL}"

payload={}
files=[
  ('file',('filename',open('/pathtofile/filename','rb'),'application/{FILE_TYPE}'))
]
headers = {
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)

For multiple variables within your filepath, you can simply concat two or more strings, just define your variables and concat them in the filepath and you'd be good to go.

Like:

folder = "abc"
filepath = "C:/Users/xyz/" + abc 

You can concat as many strings as you'd like. And therefore, inside the files list, you can simply replace the string inside open() function with your filepath variable, so your files list would become:

files=[
  ('file',('filename',open(filepath,'rb'),'application/{FILE_TYPE}'))
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...