我正在寻找一种方法来添加某种适用于所有实例的装饰器requests.get
被用在任何函数中。
例如,
@my_custom_decorator
def hello():
...
r = requests.get('https://my-api-url')
...
The my_custom_decorator
然后可以为所有实例添加一个公共参数(或其他任何参数)requests.get
。只需要在任意位置添加装饰器即可requests.get
正在使用中。
现在,我正在考虑以某种方式检查原始函数是否包含requests.get
,但这似乎并不理想。
Note:另外,我希望不要更改任何现有的实例requests.get
..因此寻找更好的方法来实现这一目标。
您可以使用unittest.mock.patch
作为函数的装饰器,其中requests.get
需要额外参数:
import requests
from unittest.mock import patch
def get(url, params=None, orig_get=requests.get, **kwargs):
return orig_get(url, {**(params or {}), 'extra_param': 'extra_value'}, **kwargs)
my_custom_decorator = patch('requests.get', get)
so that:
@my_custom_decorator
def hello():
r = requests.get('https://my-api-url', {'foo': 'bar'})
print(r.status_code)
hello()
会向 Web 服务器发送 GET 请求my-api-url
具有以下 URI:
/?foo=bar&extra_param=extra_value
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)