все Python 3urllib.requestпонятие
urllib.request.HTTPDigestAuthHandler
аутентификация
Отвечает на 401 с WWW-Authenticate: Digest — повторяет запрос с хешированным ответом на вызов сервера.
Синтаксис
urllib.request.HTTPDigestAuthHandler(password_mgr=None)
Если в opener есть и он, и HTTPBasicAuthHandler, Digest пробуется первым — его handler_order 490 против 500 у Basic; при повторном 40x очередь доходит до Basic. На вызов с другой схемой, кроме Digest и Basic, он поднимает ValueError. Пароль хешируется, но MD5 слаб — данные всё равно шлите по HTTPS.
Примеры
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')
if auth:
print(auth[:17]) # → Digest username="
return reply(req, 200, b'ok')
return reply(req, 401, WWW_Authenticate='Digest realm="api", nonce="n1", qop="auth"')
mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, 'http://example.com/', 'u', 'p')
opener = urllib.request.build_opener(Server, urllib.request.HTTPDigestAuthHandler(mgr))
print(opener.open('http://example.com/').read()) # → b'ok'
import urllib.request
print(urllib.request.HTTPDigestAuthHandler.handler_order,
urllib.request.HTTPBasicAuthHandler.handler_order) # → 490 500
См. также
Частые ошибки
Открыть в полном глоссарииdocs.python.orgСообщить о неточности