Python Glossary English

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

urllib.request.ProxyBasicAuthHandler

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

Basic-авторизация на прокси: отвечает на 407 с Proxy-Authenticate и повторяет запрос с Proxy-Authorization.

Синтаксис

urllib.request.ProxyBasicAuthHandler(password_mgr=None)

Его легко спутать с HTTPBasicAuthHandler: тот отвечает за сам сайт и код 401, этот — за прокси и код 407, и пароль от прокси в первый не подходит. Часто проще вписать логин прямо в адрес прокси: ProxyHandler({'http': 'http://user:pass@proxy:3128'}) — urllib сам добавит заголовок.

Примеры

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')
        print('Proxy-Authorization:', auth)
        if auth:
            return reply(req, 200, b'ok')
        return reply(req, 407, Proxy_Authenticate='Basic realm="proxy"')
mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, 'example.com', 'u', 'p')
opener = urllib.request.build_opener(Proxy, urllib.request.ProxyBasicAuthHandler(mgr))
opener.open('http://example.com/')
# → Proxy-Authorization: None / Proxy-Authorization: Basic dTpw

См. также

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