为什么Python:requests.post会导致406错误

为什么Python:requests.post会导致406错误,python,curl,post,python-requests,Python,Curl,Post,Python Requests,我可能太老了,不适合做这个,但我正在努力学习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

我可能太老了,不适合做这个,但我正在努力学习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'}
我做错了什么?打字错误无知?

为什么在单引号中打开(文件名)?应该是这样的:

 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'}


我改变了我在OP中尝试的语法。我真的不确定正确的语法:何时使用()和{},何时使用引号,何时不使用引号。当我尝试按Minu的建议逐字记录时,我得到了一个括号不匹配的错误。当我尝试shekhar chander建议的替换时,我得到了相同的406错误。很抱歉让你困惑。我错过了一场比赛。我修复了它。
files={'filename':open('/Users/mnewman/Desktop/myports.txt','rb')}
。在这里,
'filename'
是一个字符串,指示文件名是什么。因为它应该是一个字符串,所以它应该在queto中。