Python Flask装饰器登录验证
from flask import Flask,render_template,redirect,request,session app = Flask(__name__) app.secret_key = "sdfasdfasdf3fsdf" @app.route('/') def hello_world(): return 'Hello World!' def wapper(func): def inner(*args,**kwargs): if not session.get('user_info'): return redirect('/login') return func(*args,**kwargs) return inner @app.route('/login',methods=['GET','POST']) def login(): if request.method == "GET": return render_template('login.html') else: user = request.form.get('username') pwd = request.form.get('password') if user == 'alex' and pwd == '123': session['user_info'] = user return redirect('/index') else: return render_template('login.html',msg='用户或密码错误') @app.route('/index',methods=['GET']) @wapper def index(): return render_template('index.html') @app.route('/query',methods=['GET']) def query(): if not session.get('user_info'): return redirect('/login') return 'query' @app.route('/student',methods=['GET']) @wapper def student(): return 'student' if __name__ == '__main__': app.run()
上面方面使用装饰器会有一个弊端:
"AssertionError: View function mapping is overwriting an existing endpoint function"如何解决
为什么会出现这样的问题:
使用Flask定义URL的时候,如果出现"AssertionError: View function mapping is overwriting an existing endpoint function"这个异常信息,就说明定义了多个同名的视图函数,只需要改成不同的函数名即可。 这是为什么呢? 原来flask中url跟视图函数并不是直接对应的,而是有一个中间者-endpoint。 三者之间的关系是这样的: ``` url---->endpoint---->view_function ``` 它们是一对一的关系,在注册add_url_rule的时候,如果不指定endpoint,那么endpoint就会默认为函数名字,如果同一个endpoint于多个url注册的话,就会发生冲突,从而抛出异常。
解决方法:
from flask import Flask,render_template,redirect,request,session app = Flask(__name__) app.secret_key = "sdfasdfasdf3fsdf" @app.route('/') def hello_world(): return 'Hello World!' @app.route('/login',methods=['GET','POST']) def login(): if request.method == "GET": return render_template('login.html') else: user = request.form.get('username') pwd = request.form.get('password') if user == 'alex' and pwd == '123': session['user_info'] = user return redirect('/index') else: return render_template('login.html',msg='用户或密码错误') def wapper(func): def inner(*args,**kwargs): if not session.get('user_info'): return redirect('/login') return func(*args,**kwargs) return inner @app.route('/index',methods=['GET'],endpoint='index') @wapper def index(): return render_template('index.html') @app.route('/query',methods=['GET'],endpoint='query') @wapper def query(): if not session.get('user_info'): return redirect('/login') return 'query' @app.route('/student',methods=['GET'],endpoint='student') @wapper def student(): return 'student' if __name__ == '__main__': app.run()