我正在尝试使用python 3从teamcity下载zip工件,但是我运气不高。
在浏览器中,我通常会这样做:http:// USERNAME:PWD@SERVER/httpAuth/repository/downloadAll/dood_dad/latest.last
但是,如果我使用urllib.request.urlretrieve尝试此操作,则会收到有关无效端口的异常-因为它不知道附加在url前面的用户名和密码,并且会在':'之后作为端口进行解析-很公平。
所以我想我需要使用teamcitys httpAuth的东西,并使用url http://SERVERNAME/httpAuth/repository/downloadAll/dood_dad/latest.last
当我尝试该操作时,我得到了404 Unauthorized,这是我期望的,因为我需要提供用户名和密码。
但是我不知道怎么做。
我添加了这个:
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(None,
uri=url_to_open,
user='userame',
passwd='password')
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
local_filename, headers = urllib.request.urlretrieve(url)
但是我仍然收到HTTP错误401:未经授权
TIA。
这行得通:
import urllib
from urllib.request import HTTPPasswordMgrWithDefaultRealm
pwdmgr = HTTPPasswordMgrWithDefaultRealm()
pwdmgr.add_password(None, uri=url, user='XXXX', passwd='XXXX')
auth_handler = urllib.request.HTTPBasicAuthHandler(pwdmgr)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
local_filename, headers = urllib.request.urlretrieve(url)
我不完全确定为什么更新的代码能在较旧的代码上起作用。
仅供参考:请求代码也无法正常工作
response = requests.get('http://...', auth=HTTPBasicAuth('user', 'pass'), stream=True)
我不断收到未经授权的HTTP错误
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句