Skip to main content
 首页 » 编程设计

python之使用 Python 请求库发布请求返回状态 405

2024年10月01日10jillzhang

我正在使用 Python 中的请求库将文件上传到服务器。我阅读了它的文档和一些 stackoverflow 问题并实现了以下代码:

url = "http://example.com/file.csv" 
id = "user-id" 
password = "password" 
headers = {'content-type': 'application/x-www-form-urlencoded'} 
 
with open(file_path, 'rb') as f: 
    response = requests.post(url=url, files={'file':f}, auth=HTTPBasicAuth(username=id, password=password),headers=headers) 

但此代码无效,response.status_code 返回 405,response.reason 返回 Method Not Allowed。当我在终端上使用 curl 命令上传文件时,它工作正常并且文件被上传:

curl -u user-id:password -T file/path/on/local/machine/file.csv "http://example.com/file.csv" 

有人可以帮忙吗

请您参考如下方法:

相关问题here .实际上,curl --upload-file 执行的是 PUT 而不是 POST。如果您想模仿 curl 的作用,您可能想尝试:

with open(file_path, 'rb') as f: 
    response = requests.put(url=url, files={'file':f}, auth=HTTPBasicAuth(username=id, password=password), headers=headers)