[英]Python requests.post() returns <Response [406]>
[英]Why does Python: requests.post result in 406 Error
我可能太老了,但我正在努力学习 Python。 我在 bash 工作了很长时间。
作为练习,我尝试在 Python 中重写 bash 脚本。 该脚本所做的其中一件事是使用 curl 将文件上传到 web 主机。 它是如此容易:
curl -n -T $file $host
这就是我在 Python 中尝试的:
import requests
filename='/Users/mnewman/Desktop/myports.txt'
user='username'
password='password'
myurl='https://www.example.com/public_html/'
r=requests.post(url=myurl, data={}, files={'filename': open('/Users/mnewman/Desktop/myports.txt', 'rb')}, auth=(user, password))
print(r.status_code)
print(r.headers)
这是返回的内容:
406
{'Date': 'Sat, 12 Dec 2020 03:52:17 GMT', 'Server': 'Apache', 'Content-Length': '226', 'Keep-Alive': 'timeout=5, max=75', 'Connection': 'Keep-Alive', 'Content-Type': 'text/html; charset=iso-8859-1'}
我做错了什么? 错字? 无知?
为什么 open(filename) 在单引号内? 它应该是这样的:
f = open(filename,'rb')
当您上传文件时,它应该是二进制格式
您应该检查两件事。
首先,文件内容应该以rb
的形式打开。
其次,我还假设文件的 JSON 值的键可能不是filename
而是'filename'
。
import requests
user='username'
password='password'
myurl='http://www.example.com/public_html/'
r=requests.post(url=myurl, data={}, files={'filename': open('/Users/mnewman/Desktop/myports.txt', 'rb')}, auth=(user, password))
print(r.status_code)
print(r.headers)
事实证明,406 错误是由于需要用户代理。 添加用户代理后,406 错误就消失了。 不幸的是,文件仍然没有上传。 我将在该问题上发布一个不同的问题:
myurl='https://www.mgnewman.com/'
r=requests.post(url=myurl, data={},
files={'file': open('/Users/mnewman/Desktop/myports.txt', 'rb')},\
auth=(user, password), headers={"user-agent":"Mozilla/5.0 \
(Macintosh;\ Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 \
(KHTML, like Gecko) Version/14.0.1 Safari/605.1.15"})
print(r.status_code)
print(r.headers)
这是回应:
200
{'Date': 'Sat, 12 Dec 2020 22:08:54 GMT', 'Server': 'Apache', 'Upgrade':
'h2,h2c', 'Connection': 'Upgrade, Keep-Alive', 'Last-Modified': 'Sun, 30 Aug
2020 23:31:39 GMT', 'Accept-Ranges': 'bytes', 'Vary': 'Accept-Encoding',
'Content-Encoding': 'gzip', 'Content-Length': '1227', 'Keep-Alive':
'timeout=5, max=75', 'Content-Type': 'text/html'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.