简体   繁体   中英

Why does Python: requests.post result in 406 Error

I'm probably too old for this, but I'm trying to learn Python. I am a long time tyro at bash.

As an exercise I am attempting to rewrite a bash script in Python. One of the things the script does is upload a file to a web host using curl. It's so easy:

curl -n -T $file $host

This is what I'm trying in 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)

This is what gets returned:

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

What have I done wrong? Typo? Ignorance?

Why is open(filename) inside single quotes? It should be like:

 f = open(filename,'rb')

As you are uploading a file, it should be in binary format

There are two things you should check.
First, file contents should be open as rb .
Second, I also assume that the key of JSON value for files might be not filename but '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)

It turns out that the 406 error was due to the need for a user agent. Once I added a user agent, the 406 error went away. Unfortunately, the file still does not upload. I'll post a different question on that issue:

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)

Here's the response:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM