您的位置:首页技术文章
文章详情页

curl - Python request 上传文件

【字号: 日期:2022-09-18 16:49:55浏览:81作者:猪猪

问题描述

我尝试用 curl 提交成功

curl --form file=@/home/test/sample.png --form username=test@noreply.com --form password=test --insecure --form lang[0]=cn --form lang[1]=jp --form langs[2]=en https://www.example.com/api

但我用 requests 尝试了以下方法,却得不到正确结果。请问正确的应该怎么写?

data = { ’file’: open(’/home/test/test.png’,’rb’), ’username’: ’test@noreply.com’, ’password’: ’test’, ’lang[0]’: ’cn’, ’lang[1]’: ’jp’, ’lang[2]’: ’en’}r = requests.post(’https://www.example.com/api’, data=data, verify=False)

file = { ’file’: open(’/home/test/test.png’,’rb’) }data = { ’username’: ’test@noreply.com’, ’password’: ’test’, ’lang[0]’: ’cn’, ’lang[1]’: ’jp’, ’lang[2]’: ’en’}r = requests.post(’https://www.example.com/api’, data=data, files=file, verify=False)

另外我用 httpbin 测试,curl代码 和 第二段代码发出的请求是一样的,但是 Python 得不到返回的 ID.

问题解答

回答1:

files = {’file’: open(’test.png’, ’rb’)}requests.post(url, files=files)

参考 http://www.python-requests.or...

http://www.python-requests.or...

回答2:

with open(’filename1’, ’rb’) as f1, open(’filename2’, ’rb’) as f2: files_to_upload = {’filename1’: f1,’filename2’: f2, }response = requests.post(url, files=files_to_upload)

标签: Python 编程
相关文章: