pythonpython-2.7cloudantpacpython-cloudant

how to make cloudant pick a .pac file?


In my python (2.7) application I make use of a Cloudant database as follows:

from cloudant.client import Cloudant

client = Cloudant('XXX', 'YYY', account='ZZZ')
client.connect()
my_db = client['my_database']
for doc in my_db: print doc

The environment in which this application runs makes use of proxy.pac which can not be bypassed. How could I make the connection to Cloudant .pac aware or how could I let Cloudant automatically look for proxy.pac?

I've found the python package PyPac (https://pypac.readthedocs.io/en/latest/) but do not have the slightest idea how I should use this in the Cloudant context.

Thanks for your ideas and help in advance.


Solution

  • Since PyPAC 0.6.0, you can use the pac_context_for_url context manager:

    from pypac import pac_context_for_url
    
    
    with pac_context_for_url('https://acct.cloudant.com'):
        # Do your Cloudant stuff
    

    Original answer:

    This should work as expected:

    import os
    
    import pypac
    
    
    # PyPAC will auto-discover the current PAC settings
    pac = pypac.get_pac()
    
    # Find the proxy for Cloudant (I use this domain but anything else would work too)
    proxies = pac.find_proxy_for_url('https://acct.cloudant.com', 'cloudant.com')
    
    # It will return something like: 'PROXY 4.5.6.7:8080; PROXY 7.8.9.10:8080'
    # Here we take the 1st one:
    proxy = 'http://{}/'.format(proxies.split()[1].rstrip(';'))
    
    # Set proxy envars
    os.environ['HTTP_PROXY'] = os.environ['HTTPS_PROXY'] = proxy
    
    # And now try Cloudant stuff