Search code examples
python-requestshttp-proxy

How to force all calls to pythons requests.get to use proxy by default?


I am using a third party library in my code to get access token (ADAL). This library has a lot of calls to requests.get and requests.post. How can I force all the calls to use user provided proxies without having to modify each call to requests.get('http://example.com', proxies=proxies).

I cannot do export HTTP_PROXY. I have to do it from within my script.


Solution

  • You could monkey patch requests.

    At the very start of your script:

    import requests
    import functools
    
    orig_get = requests.get
    
    proxies = { 
      'http': 'http://10.10.1.10:3128',
      'https': 'http://10.10.1.10:1080',
    }
    requests.get = functools.partial(orig_get, proxies=proxies)