flask(1.1)装饰器装饰多个视图函数出现的问题

1.装饰器装饰多个视图函数出现的问题

代码实例:

from flask import Flask, request, render_template, session, redirect

app = Flask(__name__)
app.secret_key = "$%@&!**"  # $%@&!**是加密字符串,可随意设置


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        session["username"] = request.form.get("username")
        return redirect("/detail")


# 自定义装饰器
def outer(func):
    def inner(*args, **kwargs):
        if session.get("username"):
            ret = func(*args, **kwargs)
            return ret
        else:
            return redirect("/login")
    return inner


@app.route("/detail", methods=["GET", ])
@outer
def detail():
    return render_template("detail.html")


@app.route("/detail2", methods=["GET", ])
@outer
def detail2():
    return "this is detail2"


if __name__ == '__main__':
    app.run(debug=True)

"""
执行结果:
AssertionError: View function mapping is overwriting an existing endpoint function: inner

结论: 用装饰器装饰多个视图函数会抛出异常, 原因是多次出现了innner函数,产生覆盖现象
"""

2.使用装饰器修复技术解决该问题

from flask import Flask, request, render_template, session, redirect
from functools import wraps

app = Flask(__name__)

app.secret_key = "~!@#$%^"


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        session["username"] = request.form.get("username")
        return redirect("/detail")


# 自定义装饰器
def outer(func):
    @wraps(func)  # 装饰器修复技术
    def inner(*args, **kwargs):
        if session.get("username"):
            ret = func(*args, **kwargs)
            return ret
        else:
            return redirect("/login")

    return inner


@app.route("/detail", methods=["GET", ])
@outer
def detail():
    return "this is detail"


@app.route("/detail2", methods=["GET", ])
@outer
def detail2():
    return "this is detail2"


if __name__ == '__main__':
    app.run()
posted @ 2019-03-03 17:39  咕噜噜~  阅读(490)  评论(0编辑  收藏  举报