login函数

@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    # POST
    user = request.form.get('user')
    pwd = request.form.get('pwd')
    if user == 'tom' and pwd == '123':
        session['user'] = user
        return redirect('/index/')
    else:
        return render_template('login.html', error='账号或密码错误')

1、判断逻辑直接写在视图函数中(low)

@app.route('/index/')
def index():
    if session.get('user'):
        return render_template('index.html')
    return redirect('/login/')

2、使用装饰器(适用于,需要登录较少的网站)

def wrapper(func):
    @wraps(func)
    def inner(*args, **kwargs):
        if not session.get('user'):
            return redirect('/login/')
        ret = func(*args, **kwargs)
        return ret
    return inner
@app.route('/index/')
@wrapper
def index():
    # if session.get('user'):
    #     return render_template('index.html')
    # return redirect('/login/')
    return render_template('index.html')

3、befer_request ===>相当于Django中的process_request

# -*- encoding: utf-8 -*-
from flask import Flask, render_template, request, redirect, session
from functools import wraps
app = Flask(__name__)
app.secret_key = 'abc'


# def wrapper(func):
#     @wraps(func)
#     def inner(*args, **kwargs):
#         if not session.get('user'):
#             return redirect('/login/')
#         ret = func(*args, **kwargs)
#         return ret
#     return inner
@app.before_request
def auth():
    if request.path == '/login/':
        return None
    if session.get('user'):
        return None
    else:
        return redirect('/login/')


@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    # POST
    user = request.form.get('user')
    pwd = request.form.get('pwd')
    if user == 'tom' and pwd == '123':
        session['user'] = user
        return redirect('/index/')
    else:
        return render_template('login.html', error='账号或密码错误')


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


@app.route('/index/')
def index():
    # if session.get('user'):
    #     return render_template('index.html')
    # return redirect('/login/')
    return render_template('index.html')
#


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