Python Glossary English

все Python 3urllib.requestпонятие

urllib.request.ProxyDigestAuthHandler

аутентификация

Digest-авторизация на прокси: отвечает на 407 с Proxy-Authenticate: Digest и повторяет запрос с хешированным ответом.

Синтаксис

urllib.request.ProxyDigestAuthHandler(password_mgr=None)

Пара к HTTPDigestAuthHandler, но для прокси: код 407 и заголовок Proxy-Authorization вместо 401 и Authorization. Менеджер паролей ищет запись по адресу прокси, а не сайта, — частая причина того, что пароль «не подставляется». Для Basic-прокси нужен ProxyBasicAuthHandler, Digest его не заменяет.

Примеры

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 Proxy(urllib.request.BaseHandler):
    handler_order = 100
    def http_open(self, req):
        auth = req.get_header('Proxy-authorization')
        if auth:
            print(auth[:17])  # → Digest username="
            return reply(req, 200, b'ok')
        return reply(req, 407, Proxy_Authenticate='Digest realm="proxy", nonce="n1", qop="auth"')
mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, 'example.com', 'u', 'p')
opener = urllib.request.build_opener(Proxy, urllib.request.ProxyDigestAuthHandler(mgr))
print(opener.open('http://example.com/').read())  # → b'ok'

См. также

Открыть в полном глоссарииdocs.python.orgСообщить о неточности