[Python-Dev] Proxy settings for urllib on Win32

Neil Hodgson nhodgson@bigpond.net.au
Thu, 13 Jul 2000 00:30:08 +1000


   Is there any reason why urllib uses environment variables for proxy
settings on Win32? Its quite unlikely they will be set up and there is a
standard registry location for this information.

   I've added retrieval of registry settings to my copy of urllib and it
seems to work OK athough I'm not running off CVS and I recall the winreg
module has changed recently. Here is the code going just after the "if
os.name == 'mac'" proxy handling.

elif os.name == 'nt':
    def getproxies():
        """Return a dictionary of scheme -> proxy server URL mappings.

        Win32 uses the registry to store proxies.

        """
        proxies = {}
        try:
            import winreg
            internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                "Software\\Microsoft\\Windows\\CurrentVersion\\Internet
Settings");
            proxyEnable = winreg.QueryValueEx(internetSettings,
"ProxyEnable")[0]
            if proxyEnable:
                # Returned as Unicode but problems occur if not converted to
ASCII
                proxyServer = str(winreg.QueryValueEx(internetSettings,
"ProxyServer")[0])
                if ";" in proxyServer:        # Individual per-protocol
settings
                    for p in string.split(proxyServer,";"):
                        protocol, address = string.split(p, "=")
                        proxies[protocol] = '%s://%s' % (protocol, address)
                else:        # Use one setting for all protocols
                    proxies['http'] = 'http://%s' % proxyServer
                    proxies['ftp'] = 'ftp://%s' % proxyServer
            internetSettings.Close()
        except:        # proxies already set up to be empty so nothing to do
            pass
        return proxies


   Neil