flask中验证用户登录的装饰器

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

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):
    @wraps(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()

posted @ 2021-01-20 15:13  哈喽哈喽111111  阅读(295)  评论(0编辑  收藏  举报