Flask-Login在我的装饰器接受参数时中断 [英] Flask-Login breaks when my decorator accepts parameters
问题描述
和(现在)完全传递授权装饰器:
<$ p $ (func):
@wraps(func)
def newfunc(* args,** kwargs):从$ functools导入包装
def authorize(func)
return func(* args,** kwargs)
return newfunc
@wraps(func)
调用允许Flask找到它正在查找的端点。到目前为止,这么好。
但是我想传递一个组名称给授权进程,当我尝试使一个接受传入的装饰器参数。这似乎是正确的语法,除非我错了:
from functools import wrapps
def group():
def real_authorize(func):
@wrap(func)
def newfunc(* args,** kwargs):
return func(* args,** kwargs)
return newfunc
return real_authorize
但是再一次Flask无法找出绝密端点:
werkzeug.routing.BuildError:Could not为端点top_secret构建网址。
我想也许它需要 @wraps(authorize)
装饰就在 def real_authorize(func)
之上,但是没有任何帮助。
有人可以帮我吗找出我的 @wraps
会出错的地方? 解决方案
函数相当于将名称重新绑定到使用该函数调用装饰器的结果。
@authorize
def top_secret():
...
#相当于
def top_secret():
...
top_secret =授权(top_secret)
您写的函数是装饰器工厂 :你可以用一个可选参数来调用它来获得一个装饰器。
@authorize()
def top_secret ):
...
#相当于
def top_secret():
...
top_secret = authorize() (top_secret)
目前,您将 top_secret
作为组
参数传递给工厂,所以你从来没有真正创建一个路线。由于没有路线,所以也没有建立网址。
Thanks to what I learned from this question, I've been able to make a Flask-Login process with a endpoint like this:
@app.route('/top_secret')
@authorize
@login_required
def top_secret():
return render_template("top_secret.html")
and (for now) a completely pass-through "authorize" decorator:
from functools import wraps
def authorize(func):
@wraps(func)
def newfunc(*args, **kwargs):
return func(*args, **kwargs)
return newfunc
The @wraps(func)
call allows Flask to find the endpoint that it's looking for. So far, so good.
But I want to pass an group name to the "authorize" process, and things go bad when I try to make a decorator that accepts incoming parameters. This seems to be the correct syntax, unless I'm mistaken:
from functools import wraps
def authorize(group=None):
def real_authorize(func):
@wraps(func)
def newfunc(*args, **kwargs):
return func(*args, **kwargs)
return newfunc
return real_authorize
But once again the error appears as Flask is unable to figure out the 'top-secret' endpoint:
werkzeug.routing.BuildError: Could not build url for endpoint 'top_secret'.
I thought perhaps it needed @wraps(authorize)
decoration right above def real_authorize(func)
, but that did nothing to help.
Can someone help me figure out where my @wraps
are going wrong?
Decorating a function is equivalent to re-binding the name to the result of calling the decorator with the function.
@authorize
def top_secret():
...
# is equivalent to
def top_secret():
...
top_secret = authorize(top_secret)
The function you've written is a decorator factory: you call it, with an optional argument, to get a decorator.
@authorize()
def top_secret():
...
# is equivalent to
def top_secret():
...
top_secret = authorize()(top_secret)
Currently, you're passing top_secret
as the group
argument to the factory, so you're never actually creating a route. Since there's no route, there's no url to build either.
这篇关于Flask-Login在我的装饰器接受参数时中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!