all Python 3urllib.requestterm
urllib.request.AbstractBasicAuthHandler
authentication
The shared part of Basic authentication for sites and proxies: it parses the challenge and repeats the request with the login and password.
Syntax
class urllib.request.AbstractBasicAuthHandler(password_mgr=None)
It is a mixin: you do not create it directly but use its subclasses HTTPBasicAuthHandler and ProxyBasicAuthHandler. Basic encodes 'user:pass' in base64 — that is not encryption, so without HTTPS anyone on the path reads the password. For a scheme other than Basic, such as Bearer, the handler raises ValueError rather than HTTPError.
Examples
import base64, urllib.request
print(issubclass(urllib.request.HTTPBasicAuthHandler,
urllib.request.AbstractBasicAuthHandler)) # → True
print(base64.b64decode('dTpw')) # → b'u:p' — заголовок Basic dTpw раскрывается так
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):
return reply(req, 401, WWW_Authenticate='Bearer realm="api"')
opener = urllib.request.build_opener(Server, urllib.request.HTTPBasicAuthHandler())
try:
opener.open('http://example.com/')
except ValueError as e:
print(str(e)[:42]) # → AbstractBasicAuthHandler does not support
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy