Python: 使用请求或 urllib3 使用身份验证下载文件

Python: download files with authentification using requests or urllib3

我是 python 的新手,需要一些帮助。在工作中,我们有一个本地服务器,我想从那里下载文件。下载之前,您需要对自己进行身份验证。 为了下载,我创建了两个脚本。带有 urllib3 的脚本工作正常,但另一个我使用 requests 的脚本却没有。 有人可以检查脚本并告诉我我做错了什么吗?谢谢。

这个有效

import urllib3
url = 'http://q32wad/documents/bills.pdf'
http = urllib3.PoolManager()
headers = urllib3.util.make_headers(basic_auth='username123:password123')
r = http.request('GET', url, headers=headers)
print("STATUS = " + str(r.status))
print("HEADERS = " + str(r.headers))

results:
STATUS = 200
HEADERS = HTTPHeaderDict({'Date': 'Sun, 05 Aug 2018 15:07:32 GMT', 'Server': 'Apache', 'Content-Length': '636', 'Content-Type': 'text/html;charset=ISO-8859-1'})

这个不行

import requests
from base64 import b64encode
url = 'http://q32wad/documents/bills.pdf'
# try 1
# r = requests.get(url, auth=('username123', 'password123'))
# r = requests.get(url)
# try 2
# headers = {'username': 'username123', 'password': 'password123'}
# r = requests.get(url, headers=headers)
# try 3
# userAndPass = b64encode(b"username123:password123").decode("ascii") 
# headers = { 'authorization' : 'Basic %s' % userAndPass }
# r = requests.get(url, headers=headers)
# try 4
c = requests.Session()
c.auth =('username123', 'password123')
r = c.get(url)
print("STATUS " + str(r.status_code))
print("HEADERS " + str(r.headers))
results:
STATUS 502
HEADERS {'Date': 'Sun, 05 Aug 2018 15:11:28 GMT', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Content-Type': 'text/html; charset="UTF-8"', 'Content-Length': '2477', 'Accept-Ranges': 'none', 'Proxy-Connection': 'close'}

你试过这个吗:Python: request basic auth doesn't work

您似乎漏掉了一步,实际上是在与服务器进行身份验证。

c = requests.Session()
c.auth =('username123', 'password123')
auth = c.post('http://' + url)
r = c.get(url)

我找到了,解决方案,针对我的情况, post 帮助我

最终工作代码如下

c = requests.Session()
c.auth =('username123', 'password123')
c.trust_env = False
r = s.get(url)

如果有人知道,"trust_env = False" 是做什么用的?