:
def security_requirements(logged_in=True,
roles=None):
def wrapper(f):
# Store the security attributes as a member of the function object
f.access_control = dict(logged_in=logged_in, roles=roles)
@functools.wraps(f)
def wrapped(*args, **kwargs):
access_result = _eval_access(logged_in, roles)
# Redirect the user to the appropriate page (Access denied/Login Required/Actual Page) based on the result
...
與此裝飾器的前一版本唯一真正的區別是在函數對象中存儲安全屬性的行。這條線在裝飾者內部是無用的。但是,現在我可以執行以下操作以從Jinja模板調用:
{% if can_access(func) %}
<li><a>...</a></li>
{% endif %}
can_access函數在Flask應用程序模塊中定義。它接收到一個字符串,它必須將其轉換爲函數對象。它是通過調用app.view_functions
:
def can_access(func):
return auth.can_access(app.view_functions[func])
這個功能應該從神社模板直接調用。因此,它需要被添加到神社的全局:
app.jinja_env.globals.update(can_access=can_access)
最後,auth.can_access
:
def can_access(f):
if not hasattr(f, 'access_control'):
return True
# Use the access_control member set by the decorator
return _eval_access(**f.access_control) == AccessResult.ALLOWED
這種解決方案意味着,訪問控制是在一個地方定義的 - 這是函數裝飾。
是'security_requirements'你的裝飾者?是否允許改變它? – twil
@twil - 是的,這是我的 – reish