7. Flask中session

A, session principle

1. Explain session

No pages when accessing the server when the server will open up a memory of memory, this memory is called the session, but this memory is associated with the browser together. This means that the browser is the browser window or browser sub-window, meaning that only allows the current session corresponding browser access, even on the same machine start of the new browser also inaccessible. And another browser also need to record the session, it would re-start one of their own session.

2. Principle

HTTP protocol is connectionless in nature, taking complete content of the current browser, and after closing the browser, the link is disconnected, and there is no mechanism to record information taken out. And when another page if needed to access the same Web site (for example, like the first page option to purchase goods, the jump to the second page to make a payment) information at this time taken out of school does not come out. So there must be a mechanism that allows pages to know the principles of session content pages.

Two, session to achieve

from flask import Flask, session
import os
from datetime import timedelta

app = Flask(__name__)
# flask使用session时, 必须设置secret_key, 项目中无需使用urandom
# 设置为24位的字符,每次运行服务器都是不同的;所以服务器启动一次上次的session就清除
app.config['SECRET_KEY'] = os.urandom(24)
# 设置session的保存时间
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)  


# 添加数据到session
# 操作的时候更操作字典是一样的
# secret_key:盐,为了混淆加密


@app.route('/')
def hello_world():
    # 默认session的时间持续31天
    session.permanent = True
    session['username'] = 'xxx'

    return 'Hello World!'


# 获取session
@app.route('/get/')
def get():
    return session.get('username')


# 删除session
@app.route('/delete/')
def delete():
    print(session.get('username'))
    session.pop('username')
    print(session.get('username'))
    return 'delete'


# 清除session
@app.route('/clear/')
def clear():
    print(session.get('username'))
    session.clear()
    print(session.get('username'))
    return 'clear'


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

Guess you like

Origin www.cnblogs.com/hq82/p/12641826.html