Python:如何使用decorator使其更通用?

2024-03-29 12:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我有这个代码

@app.route("/protect1")
def protect1():
    if not session.get('logged_in'):
        session['next'] = "/protect1"
        return render_template('login.html')
    else:
        return "This is the first protected page protect1"   

@app.route("/protect2")
def protect2():
    if not session.get('logged_in'):
        session['next'] = "/protect2"
        return render_template('login.html')
    else:
        return "This is the second protected page protect2"   

在我的烧瓶应用程序中,一切正常。只是我需要为每个函数(视图)重复if/else组合并不好。你知道吗

我希望有一些通用的方法,比如这个pseude代码:

@checklogin
@app.route("/protect1")
def protect1():
    return "This is the first protected page protect1"

@checklogin
@app.route("/protect2")
def protect2():
    return "This is the second protected page protect2"

这里的一个挑战是@checklogin decorator需要知道应用程序路径路径(例如“/protect1”),以便能够正确设置会话['next']。我不知道如何将这个参数传递给decorator,尤其是如何首先找到它。换句话说,函数protect1()如何知道它是用@应用程序路径哪个参数(“/protect1”)已传递给应用程序路径装饰工?你知道吗


Tags: the路径app应用程序returnifissession
1条回答
网友
1楼 · 发布于 2024-03-29 12:21:10

decorator可以使用加载的URL(可用作^{})或^{} attributerequest上查找路径:

from functools import wraps
from flask import request, session

def checklogin(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if not session.get('logged_in'):
            session['next'] = request.url
            return render_template('login.html')
        return f(*args, **kwargs)
    return wrapper

一定要将decorator放在app.route()decorator之后,否则它将不会注册为路由的处理程序:

@app.route("/protect1")
@checklogin
def protect1():
    return "This is the first protected page protect1"

相关问题 更多 >