GreenMan
GreenMan

Reputation: 21

Python: download files with authentification using requests or urllib3

I am prety new with python and I need a little help. At work we have a local server from where I would like to download files. Before downloading you need authentificate yourself. For downloading I create two scripts. Script with urllib3 is working fine, but the other one, where I use requests doesn't. Can somebody please check the scripts and tell me what I am doing wrong. Thank you.

This one is working

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

This one is not working

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

Upvotes: 1

Views: 2620

Answers (2)

GreenMan
GreenMan

Reputation: 21

I found it, solution, for my case, this post help me

Final working code is below

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

If anybody knows, what is "trust_env = False" for?

Upvotes: 1

Spiderbro
Spiderbro

Reputation: 370

Did you try this: Python: request basic auth doesn't work

It seems like you're missing a step, actually authenticating with the server.

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

Upvotes: 0

Related Questions