@@ -382,6 +382,11 @@ The following classes are provided:
382382 ``HTTP_PROXY `` will be ignored if a variable ``REQUEST_METHOD `` is set;
383383 see the documentation on :func: `~urllib.request.getproxies `.
384384
385+ Because *proxies * holds at most one proxy for each protocol, it cannot
386+ use a proxy auto-config (PAC) file, which selects a proxy for each
387+ URL. See :ref: `this example <urllib-request-pac >` for one way to use a
388+ PAC file.
389+
385390
386391.. class :: HTTPPasswordMgr()
387392
@@ -1386,6 +1391,51 @@ programmatically supplied proxy URLs, and adds proxy authorization support with
13861391 with opener.open('http://www.example.com/login.html') as f:
13871392 print(f.read().decode('utf-8'))
13881393
1394+ .. _urllib-request-pac :
1395+
1396+ Proxy auto-config (PAC) files select a proxy for each URL, so they cannot be
1397+ described by the *proxies * mapping that :class: `ProxyHandler ` expects. The
1398+ :pypi: `pypac ` package finds and evaluates PAC files; its ``ProxyResolver ``
1399+ can be used to write a handler that consults the PAC file once per request::
1400+
1401+ import urllib.error
1402+ import urllib.request
1403+ from pypac import get_pac
1404+ from pypac.resolver import ProxyResolver
1405+
1406+ class PACProxyHandler(urllib.request.ProxyHandler):
1407+
1408+ def __init__(self, resolver):
1409+ self.resolver = resolver
1410+ # An empty mapping suppresses the <protocol>_open methods that
1411+ # ProxyHandler would make from a static proxies mapping.
1412+ super().__init__({})
1413+
1414+ def _pac_open(self, req, protocol):
1415+ proxy = self.resolver.get_proxy(req.full_url)
1416+ if proxy is None:
1417+ raise urllib.error.URLError('no proxy available')
1418+ if proxy == 'DIRECT':
1419+ return None # continue with the remaining handlers
1420+ if proxy.startswith('socks'):
1421+ raise urllib.error.URLError('SOCKS proxies are not supported')
1422+ return self.proxy_open(req, proxy, protocol)
1423+
1424+ def http_open(self, req):
1425+ return self._pac_open(req, 'http')
1426+
1427+ def https_open(self, req):
1428+ return self._pac_open(req, 'https')
1429+
1430+ opener = urllib.request.build_opener(PACProxyHandler(ProxyResolver(get_pac())))
1431+ with opener.open('http://www.example.com/') as f:
1432+ print(f.read().decode('utf-8'))
1433+
1434+ Note that a PAC file may also select a SOCKS proxy, which :mod: `urllib.request `
1435+ cannot use, and that the :envvar: `no_proxy ` environment variable and the
1436+ operating system's proxy bypass list still apply to requests the PAC file
1437+ assigned to a proxy.
1438+
13891439Adding HTTP headers:
13901440
13911441Use the *headers * argument to the :class: `Request ` constructor, or::
0 commit comments