我正在通过请求的 Session 类在 python 中访问 API。我正在使用 requests.Session() 进行 GET 和 POST 方法调用。
在每次调用(GET/POST)失败时,我想通知另一个进程。我可以通过创建一个实用方法来做到这一点,如下所示:
s = request.Session()
def post():
try:
s.post(URL,data,headers)
except:
notify_another_process()
并调用此方法而不是 requests.Session().post
直接地。
但是,我想将这段代码修改为 requests.Session().post
并希望在 requests.Session().post
中通知其他进程的附加功能方法调用自身。我怎样才能做到这一点?
编辑 1:
requests.Session() 的 post 方法具有以下签名:
def post(self, url, data=None, json=None, **kwargs):
return self.request('POST', url, data=data, json=json, **kwargs)
如果我以某种方式尝试制作如下自定义帖子:
def post_new(self, url, data=None, json=None, **kwargs):
try:
s.post(url,data, json,kwargs)
except:
notify_another_process()
然后打补丁如下:
requests.post = post_new
这不是一个很好的猴子补丁,因为我没有使用 self
但是session's object
里面session.post
.
最佳答案
这应该可以解决这个问题。您基本上用不同的名称保存旧函数,并将您的函数作为默认帖子。
setattr(requests, 'old_post', requests.post)
def post(url, data=None, json=None, **kwargs):
try:
requests.old_post(url, data, json, kwargs)
except:
notify_another_process()
setattr(requests, 'post', post)
关于Python:Monkeypatching 一个对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39850270/