Python 3.5+urllib.requestterm
urllib.request.HTTPPasswordMgrWithPriorAuth
authentication
A password store with an is_authenticated flag: with it Basic credentials are sent right away, without waiting for a 401.
Syntax
mgr.add_password(None, uri, user, passwd, is_authenticated=True)
A plain HTTPBasicAuthHandler sends the password only after a 401, and many APIs answer an unauthenticated request with 403 or 404 — then the password is never sent. add_password(..., is_authenticated=True) fixes this and saves a round trip. After a successful login the handler sets the flag itself through update_authenticated().
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):
print('запрос, Authorization:', req.get_header('Authorization'))
return reply(req, 200, b'ok')
mgr = urllib.request.HTTPPasswordMgrWithPriorAuth()
mgr.add_password(None, 'http://example.com/', 'u', 'p', is_authenticated=True)
auth = urllib.request.HTTPBasicAuthHandler(mgr)
urllib.request.build_opener(Server, auth).open('http://example.com/api')
# → запрос, Authorization: Basic dTpw
See also
Open in the full glossarydocs.python.orgReport an inaccuracy