source: sasview/src/sas/sasgui/guiframe/proxy.py @ a9f9ca4

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since a9f9ca4 was 463e7ffc, checked in by Ricardo Ferraz Leal <ricleal@…>, 8 years ago

getLogger with module name

  • Property mode set to 100644
File size: 6.2 KB
RevLine 
[957af0d]1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3import urllib2
4import sys
5import json
6import logging
7import re
8
[c155a16]9
[463e7ffc]10logger = logging.getLogger(__name__)
[c155a16]11
[957af0d]12'''
13HTTP Proxy parser and Connection
14
15connect() function:
16    - auto detects proxy in windows, osx
17    - in ux systems, the http_proxy enviroment variable must be set
18    - if it fails, try to find the proxy.pac address.
19      - parses the file, and looks up for all possible proxies
20'''
21
22
23class Connection(object):
24
25    def __init__(self, url, timeout):
26        self.url = url
27        self.timeout = timeout
28
29    def _get_addresses_of_proxy_pac(self):
30        """
31        Return a list of possible auto proxy .pac files being used,
32        based on the system registry (win32) or system preferences (OSX).
33        @return: list of urls
34        """
35        pac_files = []
36        if sys.platform == 'win32':
37            try:
38                import _winreg as winreg  # used from python 2.0-2.6
39            except:
40                import winreg  # used from python 2.7 onwards
41            net = winreg.OpenKey(
42                winreg.HKEY_CURRENT_USER,
43                "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
44            )
45            n_subs, n_vals, last_mod = winreg.QueryInfoKey(net)
46            subkeys = {}
47            for i in range(n_vals):
48                this_name, this_val, this_type = winreg.EnumValue(net, i)
49                subkeys[this_name] = this_val
50            if 'AutoConfigURL' in subkeys.keys() and len(subkeys['AutoConfigURL']) > 0:
51                pac_files.append(subkeys['AutoConfigURL'])
52        elif sys.platform == 'darwin':
53            import plistlib
54            sys_prefs = plistlib.readPlist(
55                '/Library/Preferences/SystemConfiguration/preferences.plist')
56            networks = sys_prefs['NetworkServices']
57            # loop through each possible network (e.g. Ethernet, Airport...)
58            for network in networks.items():
59                # the first part is a long identifier
60                net_key, network = network
61                if 'ProxyAutoConfigURLString' in network['Proxies'].keys():
62                    pac_files.append(
63                        network['Proxies']['ProxyAutoConfigURLString'])
64        return list(set(pac_files))  # remove redundant ones
65
66    def _parse_proxy_pac(self, pac_urls_list):
67        '''
68        For every pac file url in pac_urls_list, it tryes to connect.
69        If the connection is successful parses the file in search for
70        http proxies.
71        @param pac_urls_list: List with urls for the pac files
72        @return: list with all found http proxies
73        '''
74        proxy_url_list = []
75        for this_pac_url in pac_urls_list:
[c155a16]76            logger.debug('Trying pac file (%s)...' % this_pac_url)
[957af0d]77            try:
78                response = urllib2.urlopen(
79                    this_pac_url, timeout=self.timeout)
[c155a16]80                logger.debug('Succeeded (%s)...' % this_pac_url)
[957af0d]81            except Exception:
[c155a16]82                logger.debug('Failled (%s)...' % this_pac_url)
[957af0d]83                continue
84            pacStr = response.read()
85            possProxies = re.findall(
86                r"PROXY\s([^\s;,:]+:[0-9]{1,5})[^0-9]", pacStr + '\n')
87            for thisPoss in possProxies:
88                prox_url = 'http://' + thisPoss
89                proxy_dic = {'http': prox_url}
90                proxy_url_list.append(proxy_dic)
91        return proxy_url_list
92
93    def _set_proxy(self,proxy_dic=None):
94        '''
95        Sets connection proxy.
96        if proxy_dic is None get's teh proxy from the system.
97        To disable autodetected proxy pass an empty dictionary: {}
98        @param proxy_dic: format: {'http': 'http://www.example.com:3128/'}               
99        '''
100        if proxy_dic is None:
101            # The default is to read the list of proxies from the environment variables <protocol>_proxy.
102            # If no proxy environment variables are set, then in a Windows environment proxy settings are
103            # obtained from the registry's Internet Settings section, and in a Mac OS X environment proxy
104            # information is retrieved from the OS X System Configuration
105            # Framework.
106            proxy = urllib2.ProxyHandler()
107        else:
108            # If proxies is given, it must be a dictionary mapping protocol names to
109            # URLs of proxies.
110            proxy = urllib2.ProxyHandler(proxy_dic)
111        opener = urllib2.build_opener(proxy)
112        urllib2.install_opener(opener)
113   
114   
115   
116   
117    def connect(self):
118        '''
119        Performs the request and gets a response from self.url
120        @return: response object from urllib2.urlopen
121        '''
122        req = urllib2.Request(self.url)
123        response = None
124        try:
[c155a16]125            logger.debug("Trying Direct connection to %s..."%self.url)
[957af0d]126            response = urllib2.urlopen(req, timeout=self.timeout)
127        except Exception, e:
[c155a16]128            logger.debug("Failed!")
129            logger.debug(e)
[957af0d]130            try:
[c155a16]131                logger.debug("Trying to use system proxy if it exists...")
[957af0d]132                self._set_proxy()
133                response = urllib2.urlopen(req, timeout=self.timeout)
134            except Exception, e:
[c155a16]135                logger.debug("Failed!")
136                logger.debug(e)
[957af0d]137                pac_urls = self._get_addresses_of_proxy_pac()
138                proxy_urls = self._parse_proxy_pac(pac_urls)
139                for proxy in proxy_urls:
140                    try:
[c155a16]141                        logger.debug("Trying to use the proxy %s found in proxy.pac configuration"%proxy)
[957af0d]142                        self._set_proxy(proxy)
143                        response = urllib2.urlopen(req, timeout=self.timeout)
144                    except Exception, e:
[c155a16]145                        logger.debug("Failed!")
146                        logger.debug(e)
[957af0d]147        if response is not None:
[c155a16]148            logger.debug("The connection to %s was successful."%self.url)
[957af0d]149        else:
[c155a16]150            logger.warning("Connection to %s failed..."%self.url)
[957af0d]151        return response
152
153
154if __name__ == "__main__":
155    from pprint import pprint
156    c = Connection()
157    response = c.connect()
158    if response is not None:
159        print 50 * '-'
160        content = json.loads(response.read().strip())
161        pprint(content)
Note: See TracBrowser for help on using the repository browser.