Python: Monkeypatching a method of an object

我是研究僧i 提交于 2019-12-06 05:09:15

This should resolve this. You basically save the old function with different name and give your function as the default 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)

You're almost there, but you should use the self argument

def post_new(self, url, data=None, json=None, **kwargs):
    try:
        return self.request('POST', url, data=data, json=json, **kwargs)
    except:
        notify_another_process()

Then set the post function to post_new

requests.post = post_new
Pankaj Singhal

This is the answer which worked for me. It is inspired by the answers mentioned by Siddharth & lafferc both. This is on top of what both of them mentioned.

>>> import requests
>>> def post(self, url, data=None, json=None, **kwargs):
...     try:
...         raise Exception()
...     except:
...         print "notifying another process"
... 
>>> setattr(requests.Session, 'post_old', requests.Session.post)
>>> setattr(requests.Session, 'post', post)
>>> s = requests.Session()
>>> s.post("url")
notifying another process
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!