用参数

时间:2017-05-16 21:45:11

标签: python flask marshalling decorator flask-restful

我试图在调用marshal_with之前用装饰器替换flask-restful来自marshal_with装饰器。我的方法是尝试实现一个包装marshal_with的新装饰器。

我的代码如下:

from flask.ext.restful import marshal_with as restful_marshal_with

def marshal_with(fields, envelope=None):
    def wrapper(f):
        print("Do something with fields and envelope")

        @wraps(f)
        def inner(*args, **kwargs):
            restful_marshal_with(f(*args, **kwargs))
        return inner
    return wrapper

不幸的是,这似乎破坏了一些事情......没有错误消息,但我的API在它不应该返回时返回null响应。关于我做错了什么的任何见解?

2 个答案:

答案 0 :(得分:0)

我不知道marshal_with的细节,但完全可以在单个函数上使用多个装饰器。例如:

def decorator_one(func):
    def inner(*args, **kwargs):
        print("I'm decorator one")
        func(*args, **kwargs)
    return inner

def decorator_two(text):
    def wrapper(func):
        def inner(*args, **kwargs):
            print(text)
            func(*args, **kwargs)
        return inner
    return wrapper

@decorator_one
@decorator_two("I'm decorator two")
def some_function(a, b):
    print(a, b, a+b)


some_function(4, 7)

这给出的输出是:

I'm decorator one
I'm decorator two
4 7 11

您可以在每次inner函数调用后添加print语句来修改这个小脚本,以查看每个装饰器之间的确切流控制。

答案 1 :(得分:0)

我在这里做了一些错误,首先,未能将hours_text = {0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",10:"ten",11:"eleven",12:"twelve"} closest_text = {0: "o' clock", 15:"quarter past", 30: "half past", 45: "quarter to", 60: "o' clock"} 的输出返回为jonrsharpe指出,其次,未能理解编写为类而不是函数的装饰器,以及如何正确地将值传递给它。正确的代码最终成为:

restful_marshal_with

如您所见,除了不返回def marshal_with(fields, envelope=None): def wrapper(f): print("Do something with fields and envelope") @wraps(f) def inner(*args, **kwargs): rmw = restful_marshal_with(fields, envelope) return rmw(f)(*args, **kwargs) return inner return wrapper 之外,我还需要在调用之前正确初始化rmw()类。最后,重要的是要记住装饰器返回函数,因此原始函数的参数应该传递给request_marshal_with的返回值,因此声明rmw(f)。如果您查看return rmw(f)(*args, **kwargs)代码here

,这可能会更加明显