2.8.6Flask --5 Flask的cookie与session

Flask目录:https://www.jianshu.com/p/9b5e30320849
关于什么是cookie,什么是session不在赘述。
这里是一个登录注销实例:

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

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True

# this secret key is required for using cookie and session
app.config['SECRET_KEY'] = '$%^&*()345671231adFGHJBHJK,./'


@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        user_name = request.form.get('user_name')
        password = request.form.get('password')
        print(user_name)
        resp = make_response(redirect(url_for('index')))
        
        # 设置cookie,还有存活时长。
        resp.set_cookie('username', user_name, max_age=3600)
        # 设置session
        session['password'] = password

        return resp


@app.route('/index/')
def index():
    #获取cookie与session
    user_name = request.cookies.get('username')
    password = session['password']
    if user_name and password:
        return render_template('index.html', user_name=user_name, password=password)
    else:
        response = redirect(url_for('login'))
        return response
    
@app.route('/logout/')
def logout():
    response = redirect(url_for('login'))
    #通过response删除cookie里的'username'
    response.delete_cookie('username')
    #删除session
    session.pop('password')
    return response

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

login.html




    
    Title


    
user name:
password:

index.html




    
    Title


    

Hello, {{user_name}}!

We know your password is {{password}}

注销

你可能感兴趣的:(2.8.6Flask --5 Flask的cookie与session)