如何用Python实现curl -T的PUT方式文件上传?
实现与curl -T一致的Artifactory文件上传(Python版)
背景
已通过WSL2中的curl命令成功向Artifactory上传文件:
curl -H "Authorization: Bearer <Token>" -X PUT "http://localhost:8081/artifactory/my-repository/my/new/artifact/directory/file.txt" -T Desktop/myNewFile.txt
改用Python脚本实现时执行失败,报错:
[SSL: WRONG_VERSION_NUMBER] wrong version number
Python测试代码:
headers = { 'authorization': f"Bearer {token}" } files = {'upload_file': open('dummy9.txt', 'rb')} print('Start the request') response = requests.put(url, files=files, headers=headers) print('Finished') print(response.text)
问题根源
- 请求格式不匹配:curl的
-T参数是将文件内容作为PUT请求的原始请求体发送,但Python的requests.put(files=...)会以multipart/form-data格式上传,和curl的请求结构完全不同。 - 协议不一致:curl命令使用
http协议,但Python脚本中可能误用了https协议,而目标Artifactory未配置HTTPS,导致SSL版本错误。
正确实现代码
import requests token = "你的认证令牌" # 严格匹配curl中的url,使用http协议 url = "http://localhost:8081/artifactory/my-repository/my/new/artifact/directory/file.txt" # 直接将文件内容作为PUT请求的原始body发送,与curl -T行为一致 with open('dummy9.txt', 'rb') as file_obj: headers = {'authorization': f"Bearer {token}"} print('Start the request') response = requests.put(url, data=file_obj, headers=headers) print('Finished') print(response.text) print(f"响应状态码: {response.status_code}")
核心要点
- 替换
files参数为data参数,传入打开的文件对象,确保请求体格式与curl一致。 - 必须保证url的协议(http/https)与curl完全相同,避免SSL相关错误。
- 使用
with语句管理文件句柄,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Daan
相关产品推荐
相关产品推荐

