Python:如何使其更通用-可能是使用装饰器?

Python:如何使其更通用-可能是使用装饰器?,python,flask,Python,Flask,目前我有这个代码 @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.rou

目前我有这个代码

@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组合并不好

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

@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需要知道app.route路径(例如“/protect1”),以便能够正确设置会话['next']。我不知道如何将这个参数传递给装饰者,尤其是如何首先找到它。换句话说,函数protect1()如何知道它被@app.route修饰,以及哪个参数(“/protect1”)已传递给该app.route装饰器?

装饰器可以在
请求上查找路径;使用加载的URL(可用为)或:

请务必将装饰器放在
app.route()
decorator之后,否则它将不会注册为路由的处理程序:

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

装饰器可以在
请求中查找路径
;使用加载的URL(可用为)或:

请务必将装饰器放在
app.route()
decorator之后,否则它将不会注册为路由的处理程序:

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

你能展示一下你到目前为止所做的尝试吗?我只是环顾了一下,但没有写任何东西-我不知道函数(在我的示例中是protect1())如何知道传递给其装饰器(app.route(),即发现值为“/protect1”)的参数的值…您能展示一下您到目前为止尝试了什么吗?我只是环顾了一下,但没有写任何东西-我不知道函数(在我的示例中为protect1())如何知道传递给其装饰器(app.route(),即发现值为“/protect1”)。。。