Python请求在外部库中进行配置

2024-04-26 06:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个库,比如tableauserverclient,它使用来自请求库的方法

现在假设在执行get/post方法时需要设置代理或ignoreSSL。直接使用python请求调用这些方法非常简单,但是由于tableauserverclient库调用这些方法,我通常必须更新外部库的源代码才能设置配置

是否有一种方法可以在我的外部库中全局设置请求模块的配置


Tags: 模块方法代理get源代码全局posttableauserverclient
1条回答
网友
1楼 · 发布于 2024-04-26 06:15:54

在调用实际的requests.request函数之前,您可以使用一个包装函数重写requests.request,该包装函数为proxiesverify参数指定默认值:

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
)

相关问题 更多 >