all Python 3urllib.requestterm
urllib.request.HTTPBasicAuthHandler
authentication
Answers a 401 with WWW-Authenticate: Basic by repeating the request with the login and password from the password manager.
Syntax
urllib.request.HTTPBasicAuthHandler(password_mgr=None)
The first request always goes out without the password, and only a 401 triggers a retry — a server answering 403 or 404 instead never gets the password (use HTTPPasswordMgrWithPriorAuth then). If the realm in add_password does not match the server's, you get HTTPError 401. Without an argument it creates its own empty manager — add the password with handler.add_password().
Examples
import email.message, io, urllib.error, urllib.request, urllib.response
def reply(req, code, body=b'', **headers):
msg = email.message.Message()
for name, value in headers.items():
msg[name.replace('_', '-')] = value
resp = urllib.response.addinfourl(io.BytesIO(body), msg, req.full_url, code)
resp.msg = 'demo'
return resp
class Server(urllib.request.BaseHandler):
handler_order = 100
def http_open(self, req):
auth = req.get_header('Authorization')
print('Authorization:', auth)
if auth:
return reply(req, 200, b'ok')
return reply(req, 401, WWW_Authenticate='Basic realm="api"')
mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, 'http://example.com/', 'u', 'p')
opener = urllib.request.build_opener(Server, urllib.request.HTTPBasicAuthHandler(mgr))
print(opener.open('http://example.com/secret').read())
# → Authorization: None / Authorization: Basic dTpw / b'ok'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy