示例#1
0
def _add_proxy(session, config):
    if None in (config.proxy_url, config.proxy_port):
        return

    # Set session.proxies according to given url and port
    protocol, remainder = urllib.splittype(config.proxy_url)
    host, remainder = urllib.splithost(remainder)
    url = ':'.join((host, str(config.proxy_port)))

    if config.proxy_username is not None:
        password_part = config.get('proxy_password', '') and ':%s' % config.proxy_password
        auth = config.proxy_username + password_part
        auth = urllib.quote(auth, safe=':')
        url = '@'.join((auth, url))

    session.proxies['https'] = '://'.join((protocol, url))
    session.proxies['http'] = '://'.join((protocol, url))

    # Set session.auth if proxy username is specified
    if config.proxy_username is not None:
        proxy_password = config.get('proxy_password', '')
        if None in (config.basic_auth_username, config.basic_auth_password):
            # bz 1021662 - Proxy authentiation using username and password in session.proxies urls
            # does not setup correct headers in the http download request because of a bug in
            # urllib3. This is an alternate approach which sets up the headers correctly.
            session.auth = requests.auth.HTTPProxyAuth(config.proxy_username, proxy_password)
        else:
            # The approach mentioned above works well except when a basic user authentication is
            # used, along with the proxy authentication. Therefore, we define and use a custom class
            # which inherits AuthBase class provided by the requests library to add the headers
            # correctly.
            session.auth = HTTPBasicWithProxyAuth(config.basic_auth_username,
                                                  config.basic_auth_password,
                                                  config.proxy_username,
                                                  proxy_password)
示例#2
0
    def test_http_basic_with_proxy_auth_config(self):
        username = '******'
        password = '******'
        proxy_username = '******'
        proxy_password = '******'
        basic_plus_proxy_config = HTTPBasicWithProxyAuth(username, password,
                                                         proxy_username, proxy_password)

        request = requests.models.Request()
        basic_plus_proxy_config(request)

        expected_authorization = requests.auth._basic_auth_str(username, password)
        expected_proxy_authorization = requests.auth._basic_auth_str(proxy_username, proxy_password)
        self.assertEquals(request.headers['Authorization'], expected_authorization)
        self.assertEquals(request.headers['Proxy-Authorization'], expected_proxy_authorization)