Python 3.5+urllib.requestпонятие
urllib.request.HTTPPasswordMgrWithPriorAuth
аутентификация
Хранилище паролей с флагом is_authenticated: с ним Basic-авторизация отправляется сразу, без ожидания ответа 401.
Синтаксис
mgr.add_password(None, uri, user, passwd, is_authenticated=True)
Обычный HTTPBasicAuthHandler шлёт пароль только в ответ на 401, а многие API на запрос без авторизации отвечают 403 или 404 — тогда пароль не уйдёт никогда. add_password(..., is_authenticated=True) решает это и экономит лишний запрос. После успешного входа обработчик сам ставит флаг через update_authenticated().
Примеры
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
См. также
Открыть в полном глоссарииdocs.python.orgСообщить о неточности