创建装饰器

时间:2014-01-23 07:40:22

标签: python python-decorators

我从HTTP GET请求中获取值。我正在检查该值是否不等于零。如果是,则发送返回消息,否则正在进行进一步处理。

def api_servers():
    installation_name = request.args.get('installation_name', '')
    if installation_name == '':
        data = {"description": "Installation Name is required"}
        return HttpResponse(json.dumps(data), status=400, mimetype='application/json')

    data = { "arms": arms_list }

    return HttpResponse(json.dumps(data), status=200, mimetype='application/json')

现在,我想使用装饰器功能检查这个条件。这就是我正在尝试的。

def wrapper(func):
    def inner(): # I dont know what to pass in the arguments. Installation_name? 
                 # Maybe? But then how do I pass Installation_name

        if installation_name == '':
            data = {"description": "Installation Name is required"}
            return HttpResponse(json.dumps(data), status=400, mimetype='application/json')

        else: 
            return func()
    return inner 

如何通过装饰师实现这一目标?

修改 当我继续进行时,我发现我需要另一个装饰器来检查data是否None。它还会检查installation_name是否为空,然后我需要“回收”这两个installation_namedata。我重新编写了你的​​代码。但价值正在互换,即data获得installation_name,反之亦然。你能看一下吗?感谢

def with_description(fn):

    def inner(*args, **kwargs):
    # Precheck
        installation_name = 'inst1'
        if installation_name == '':
            return 1

        # If precheck passes
        return fn(installation_name, *args, **kwargs)

    return inner


def with_description1(fn):

    def inner(*args, **kwargs):
    # Precheck
        data = 'data1'
        if data == '':
            return 1

        # If precheck passes
        return fn(data, *args, **kwargs)

    return inner

@with_description
@with_description1
def api_servers1(installation_name,data):
    print installation_name,data



api_servers1()

1 个答案:

答案 0 :(得分:3)

嗯,试一试:

import functools

def with_description(fn):

    @functools.wraps(fn)  # This is not strictly necessary, just pulls info (docstrings, etc) from fn and pushes into the wrapper
    def wrapper(*args, **kwargs):
        # Precheck
        installation_name = request.args.get('installation_name', '')
        if installation_name == '':
            data = {"description": "Installation Name is required"}
            return HttpResponse(json.dumps(data), status=400, mimetype='application/json')

        # If precheck passes, call the actual function
        fn(*args, **kwargs)

    return wrapper

有了这个,你就赢了,所有装饰的功能实际上只有在预检通过时才被调用。

修改

如果注释,您想要回收安装名称,则只需将其传递给函数调用。一种可能性如下:

fn(installation_name, *args, **kwargs)

当然,装饰函数必须期待这个论点。