Sixty-one: Flask.Session the flask operating session

 

1, disposed session: use the dictionary flask.session can operate as the operation mode and operating the dictionary: the session [ 'Key'] = value
2, obtaining the session, and obtain the value of the dictionary as: session [ 'key'], session. GET ( 'Key')
. 3, remove the value of the session: and deleting dictionary values as
  session.pop (key): delete the specified value
  del session [key]: Deletes the specified value
  Session.clear (): delete all the session value
4, set the session valid: If you do not set the validity period, the default browser is closed after the failure, if you set session.permanent = True then expire in 31 days, if you want to specify the validity period, by configuring the realization (to be set session.permanent = True), provided as two hours after the expiration: app.config [ 'PERMANENT_SESSION_LIFETIME'] = timedelta (hours = 2)

 

1, disposed session: use the dictionary flask.session can operate, the operation mode of operation and a dictionary: session [ 'key'] = value

import os
from flask import Flask, session

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(30)


@app.route('/')
def index():
session['username'] = 'xxxxxxxxxxxx'
return 'hello world'

 

2, obtaining the session, and obtain the value of the dictionary as: session [ 'key'], session.get ( 'key')

import os
from flask import Flask, session

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(30)


@app.route('/get_session/')
def get_session():
username = session.get('username', '没有获取到username')
return f'获取的session为:{username}'

 

3, delete the value in the session: delete the specified session or delete the contents of all of the information session

OS Import 
from the Flask Flask Import, the session

App = the Flask (__ name__)
the app.config [ 'of SECRET_KEY'] = os.urandom (30)


@ app.route ( '/ delete_session /')
DEF delete_session ():
session.pop ( ' username ') # delete the contents of the specified session in the
# session.clear () # remove everything session of
return' deleted successfully '

 

4, set the session's validity

OS Import 
from the Flask Flask Import, the session

App = the Flask (__ name__)
the app.config [ 'of SECRET_KEY'] = os.urandom (30)


@ app.route ( '/')
DEF index ():
the session [ 'username'] = 'xxxxxxxxxxxx'
session.permanent # default = True False, if set to True, it will store 31 days
return 'hello world'

 

Specified expiration time

 

Guess you like

Origin www.cnblogs.com/zhongyehai/p/11853995.html