用相同的装饰器“烧瓶”路由到view_func。 [英] Route to view_func with same decorators "flask"

查看:225
本文介绍了用相同的装饰器“烧瓶”路由到view_func。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  app.add_url_rule('/',
view_func = index,
methods = ['GET'])

app.add_url_rule('login',
view_func = login,
methods = ['GET','POST' ])

@validate_access()
def index():
#......

@validate_access()
def login():
...... ......

同样的装饰@validate_access。
当我运行这段代码时,我得到了:

$ pre $ AssertionError:视图函数映射覆盖了现有的端点函数:wrapperAssertionError:View函数映射是覆盖现有的端点函数:包装

我不知道它是否有bug 。但请告知我是否有解决方案。



谢谢:)

解决方案

如果您不提供端点 add_url_rule route ,该方法的名称将被用作端点。发生了什么事是规则正在创建您的包装函数的名称,而不是装饰功能,可能是因为您没有使用 functools.wraps

  from functools进口包装
def my_decorator(f):
@wraps(f)
def包装(* args,** kwds):
返回f(* args,** kwds )
返回包装


lets suppose i have this routes:

app.add_url_rule('/',
                  view_func=index,
                  methods=['GET'])

app.add_url_rule('login',
                  view_func=login,
                  methods=['GET', 'POST'])

@validate_access()
def index():
    #......

@validate_access()
def login():
    #......

I have 2 endpoints with same decorator "@validate_access". When i run this code i got

AssertionError: View function mapping is overwriting an existing endpoint function:    wrapperAssertionError: View function mapping is overwriting an existing endpoint function: wrapper

I don't know if its a bug or not. But please inform me if there is a solution for this.

Thanks :)

解决方案

If you dont provide endpoint to add_url_rule or route, the name of the method will be used as the endpoint. What's happening is the rule is being created with the name of your wrapping function, rather than the decorated function, probably because you arent using functools.wraps

from functools import wraps
def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        return f(*args, **kwds)
    return wrapper

这篇关于用相同的装饰器“烧瓶”路由到view_func。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆