【问题标题】:python: decorate an existing method of a modulepython:装饰模块的现有方法
【发布时间】:2017-11-28 20:38:00
【问题描述】:

我的应用程序对请求方法(get、post、put、delete)有很多调用。我想点击这些调用来打印出我的应用程序中所有调用的调试/跟踪信息。

我在 venv 中运行所有内容,因此一个明显的选择是转到 venv 中的 reqeusts 模块,并使用可以执行必要日志记录的函数来装饰这 4 个方法。

还有其他方法可以实现吗?

import requests

# do some magic to install a decorative method for requests.get

requests.get('http://google.com')

应该会导致装饰器收到调用来进行必要的日志记录。

我查看了 patch / flexmock / requests_mock 但似乎我需要提供该方法的替代实现。我需要的是一种装饰现有方法的方法。

【问题讨论】:

标签: python python-2.7


【解决方案1】:

装饰器只是一个返回另一个函数的函数:

def decorator(f):
    def inner(*args, **kwargs):
        print(args, kwargs)
        return f(*args, **kwargs)
    return inner

requests.get = decorator(requests.get)
requests.get('http://google.com')

(('http://google.com',), {})
<Response [200]>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 2012-01-28
    • 2018-07-14
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多