Search code examples
pythonauthenticationproxygeopy

Using geopy with password authenticated proxy


I'm trying to use geopy with a set of coordinates and everything works fine at first.

from geopy.geocoders import GoogleV3
# some coordinates as example
latitude, longitude = 24.47646, 85.3095
geolocator = GoogleV3()
location = geolocator.geocode('%s, %s' (latitude, longitude))
address = location.address
print address
# this would print something like 
Unnamed Road, Burhia Ahri, Jharkand 825406, India

The enviroment I'm working on requires an authenticated proxy, for example purposes let's say something like

proxy_address = 'http://proxy.tests.mydomain'
proxy_port = 3128
proxy_user = 'my_user'
proxy_pass = 'my_pass'

Asuming the requirement of authenticated proxy to make it work, I've looked at geopy github page and the docs and even if proxies are mentioned, not a single valid url is found.

It seems like sending a dictionary with the 'proxies' parameter is supported, but there is no user/password authenticated variant mentioned anywhere.

Is there any way that something like this is doable?

geolocator = GoogleV3(proxies={'http': proxy_address,
                               'password': my_user + my_pass})

Edit: Spelling


Solution

  • For those who may encounter the same problem, I've found a solution to my problem that involves playing with the os module.

    import os
    def set_proxy():
        proxy_addr = 'http://{user}:{passwd}@{address}:{port}'.format(
            user='user_example', passwd='pass_example', 
            address='address_example', port=int('port_example'))
        os.environ['http_proxy'] = proxy_addr
        os.environ['https_proxy'] = proxy_addr
    
    def unset_proxy():
        os.environ.pop('http_proxy')
        os.environ.pop('https_proxy')
    
    set_proxy()
    geolocator = GoogleV3()
    location = geolocator.geocode('%s, %s' % (latitude, longitude), timeout=10)
    address = location.address
    unset_proxy()