Python Glossary Русский

all Python 3urllib.requestterm

urllib.request.ProxyBasicAuthHandler

authentication

Basic authentication against a proxy: it answers a 407 with Proxy-Authenticate and repeats the request with Proxy-Authorization.

Syntax

urllib.request.ProxyBasicAuthHandler(password_mgr=None)

It is easy to confuse with HTTPBasicAuthHandler: that one is for the site itself and code 401, this one for the proxy and code 407, and a proxy password in the first one does nothing. It is often simpler to put the login into the proxy address: ProxyHandler({'http': 'http://user:pass@proxy:3128'}) — urllib adds the header itself.

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 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

See also

Open in the full glossarydocs.python.orgReport an inaccuracy