curl - Python request 上传文件
怪我咯
怪我咯 2017-04-18 10:20:14
[Python讨论组]

我尝试用 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.

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
巴扎黑
files = {'file': open('test.png', 'rb')}
requests.post(url, files=files)

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

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

PHPz
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)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号