G
G
GermanW2014-01-21 05:17:18
Python
GermanW, 2014-01-21 05:17:18

How to implement file upload with basic http authorization in python 3?

Hello
, I have the following problem: I need to download a file from the http server by url, but it is under http basic auth.
If I use a browser to follow a link like this:
http://'login':'pass'@moyserver.com/file.file
The file is downloaded, if in the script:

import urllib.request
serv = 'мой сервер'
Username = 'логин'
Password = 'пароль'
file='полный адрес файла(с директорией)'
site='http://'+Username+':'+Password+'@'+serv+file
n=file.split('/')#Не уверен что красиво, но позволяет быстро отделить имя файла
file=n[-1] 
def load(filename,site):
    with urllib.request.urlopen(site) as url:
     s = url.read()
    f = open(filename, "wb")
    f.write(s)
    f.close()
 load(file,site)

The script gives an error (the password is trying to use as a connection port).
I found recipes for 2.6, but I can't figure out how to implement it in 3.
I'm just learning the snake, and I would appreciate advice on where to dig.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
s0L, 2014-01-21
@GermanW

Very simple

request = Request("http://your_site.ru")
auth = b64encode(bytes("user:password", "ascii")).decode("ascii")
request.add_header("Authorization", "Basic %s" % auth)
response = urlopen(request)

_
_ _, 2014-01-21
@AMar4enko

See
docs.python.org/dev/library/urllib.request.html#ur...

G
GermanW, 2014-01-22
@GermanW

Thanks for the help, @AMar4enko I really need to figure out what you gave me... but it's still hard. @s0L your answer is right on point, thank you all for your efforts, but please read the text of the question carefully.
Thank you for your help. german white

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question