h33
h33

Reputation: 1344

Python requests configuration within external libraries

Suppose I have a library such as tableauserverclient, and it uses methods from the requests library.

Now say I need to set a proxy or ignoreSSL when performing a get/post method. This is pretty simple calling the methods directly with python requests, but since the tableauserverclient library calls the methods I usually have to update the source code of the external library in order to set the configuration.

Is there a way that I can globally set the configuration of the requests modules across my external libraries?

Upvotes: 2

Views: 173

Answers (1)

blhsing
blhsing

Reputation: 107005

You can override requests.request with a wrapper function that assigns default values to the proxies and verify arguments before calling the actual requests.request function:

import requests
import inspect

def override(self, func, proxies, verify):
    def wrapper(*args, **kwargs):
        bound = sig.bind(*args, **kwargs)
        bound.apply_defaults()
        bound.arguments['proxies'] = bound.arguments.get('proxies', proxies)
        bound.arguments['verify'] = bound.arguments.get('verify', verify)
        return func(*bound.args, **bound.kwargs)

    sig = inspect.signature(func)
    return wrapper

requests.request = override(
    requests.request,
    proxies={'http': 'http://example-proxy.com', 'https': 'http://example-proxy.com:1080'},
    verify=False
)

Upvotes: 2

Related Questions