Flask 通过扩展来实现登录验证

1. flask扩展

说明:

flask的扩展类似于python中的装饰器,和Django中的process_request的方法也类似

测试代码

from flask import Flask,session,Session,flash,get_flashed_messages,redirect,render_template,request
app = Flask(__name__)
app.secret_key ='sdfsdfsdf'

@app.before_request
def process_request1():
    print('process_request1')

@app.after_request
def process_response1(response):
    print('process_response1')
    return response


@app.before_request
def process_request2():
    print('process_request2')

@app.after_request
def process_response2(response):
    print('process_response2')
    return response


@app.route('/index')
def index():
    print('index')
    return 'Index'

@app.route('/order')
def order():
    print('order')
    return 'order'

@app.route('/test')
def test():
    print('test')
    return 'test'

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

在浏览器中访问index结果:

process_request1
process_request2
127.0.0.1 - - [04/Jan/2018 15:48:53] "GET / HTTP/1.1" 404 -
process_response2
process_response1
127.0.0.1 - - [04/Jan/2018 15:48:58] "GET /index HTTP/1.1" 200 -
process_request1
process_request2
index
process_response2
process_response1

实际使用案例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:supery

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

app = Flask(__name__)
# 使用session需要配置secret_key
app.secret_key ='sdfsdfsdf'

@app.route('/login',endpoint='login',methods=['POST','GET'])
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信息
            session['user_info'] = {'user':user,'userID':1}
            return redirect('index')
        return render_template('login.html')


@app.before_request
def process_request():
    if request.path == '/login':
        return None
    if not session.get('user_info'):
        return redirect('login')


@app.after_request
def process_response(response):
    print('写扩展程序')
    return response

@app.route('/index',endpoint='index',methods=['GET','POST'])
def index():
    return 'index'


@app.route('/query',endpoint='query',methods=['GET','POST'])
def query():
    return 'query'

@app.route('/student',endpoint='student',methods=['GET','POST'])
def student():
    return 'student'

if __name__ == '__main__':
    app.run()
扩展登录验证

 

posted @ 2018-01-04 15:51  Pythia丶陌乐  阅读(1210)  评论(0编辑  收藏  举报