The specific use of Flask flask ES2en

  • 2020-11-18 06:21:35
  • OfStack

flask-session is an session component of the flask framework. Since session was originally built in flask and saved using signature cookie, this component will save support for session in several places, such as:

redis memcached filesystem mongodb sqlalchmey

The installation


pip3 install flask-session 

storage

redis


#!/usr/bin/env python
# -*- coding:utf-8 -
import redis
from flask import Flask, session
from flask_session import Session
 
app = Flask(__name__)
app.debug = True
app.secret_key = 'xxxx'
 
app.config['SESSION_TYPE'] = 'redis' # session A type of redis
app.config['SESSION_PERMANENT'] = False #  If I set it to True , close the browser session Is failure. 
app.config['SESSION_USE_SIGNER'] = False #  Whether to send the pair to the browser session the cookie Value encrypted 
app.config['SESSION_KEY_PREFIX'] = 'session:' #  Save to session The prefix of the value in 
app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port='6379', password='123123') #  Used to connect to redis The configuration of the 
 
Session(app)
 
@app.route('/index')
def index():
  session['k1'] = 'v1'
  return 'xx'
 
if __name__ == '__main__':
  app.run() 

memcached


#!/usr/bin/env python
# -*- coding:utf-8 -
import redis
from flask import Flask, session
from flask_session import Session
import memcache
 
app = Flask(__name__)
app.debug = True
app.secret_key = 'xxxx'
 
app.config['SESSION_TYPE'] = 'memcached' # session A type of redis
app.config['SESSION_PERMANENT'] = True #  If I set it to True , close the browser session Is failure. 
app.config['SESSION_USE_SIGNER'] = False #  Whether to send the pair to the browser session the cookie Value encrypted 
app.config['SESSION_KEY_PREFIX'] = 'session:' #  Save to session The prefix of the value in 
app.config['SESSION_MEMCACHED'] = memcache.Client(['10.211.55.4:12000']) 
 
Session(app) 
 
@app.route('/index')
def index():
  session['k1'] = 'v1'
  return 'xx'
 
if __name__ == '__main__':
  app.run() 

filesystem


#!/usr/bin/env python
# -*- coding:utf-8 -
import redis
from flask import Flask, session
from flask_session import Session
 
app = Flask(__name__)
app.debug = True
app.secret_key = 'xxxx'
 
app.config['SESSION_TYPE'] = 'filesystem' # session A type of redis
app.config[
  'SESSION_FILE_DIR'] = '/Users/wupeiqi/PycharmProjects/grocery/96.Flask The new curriculum / component /2.flask-session' # session A type of redis
app.config['SESSION_FILE_THRESHOLD'] = 500 #  storage session If it's greater than that, then we're going to start deleting it 
app.config['SESSION_FILE_MODE'] = 384 #  File permission type 
 
app.config['SESSION_PERMANENT'] = True #  If I set it to True , close the browser session Is failure. 
app.config['SESSION_USE_SIGNER'] = False #  Whether to send the pair to the browser session the cookie Value encrypted 
app.config['SESSION_KEY_PREFIX'] = 'session:' #  Save to session The prefix of the value in 
 
Session(app) 
@app.route('/index')
def index():
  session['k1'] = 'v1'
  session['k2'] = 'v1'
  return 'xx'
 
if __name__ == '__main__':
  app.run() 

mongodb


#!/usr/bin/env python
# -*- coding:utf-8 -
import redis
from flask import Flask, session
from flask_session import Session
import pymongo
app = Flask(__name__)
app.debug = True
app.secret_key = 'xxxx'
 
app.config['SESSION_TYPE'] = 'mongodb' # session A type of redis
 
app.config['SESSION_MONGODB'] = pymongo.MongoClient()
app.config['SESSION_MONGODB_DB'] = 'mongo the db Name (Database name) '
app.config['SESSION_MONGODB_COLLECT'] = 'mongo the collect Name (Table name) '
 
app.config['SESSION_PERMANENT'] = True #  If I set it to True , close the browser session Is failure. 
app.config['SESSION_USE_SIGNER'] = False #  Whether to send the pair to the browser session the cookie Value encrypted 
app.config['SESSION_KEY_PREFIX'] = 'session:' #  Save to session The prefix of the value in 
 
Session(app)
 
@app.route('/index')
def index():
  session['k1'] = 'v1'
  session['k2'] = 'v1'
  return 'xx'
 
if __name__ == '__main__':
  app.run() 

Simple example of mongodb operation:


#!/usr/bin/env python
# -*- coding:utf-8 -*-
from pymongo import MongoClient
 
#  Create links 
conn = MongoClient('47.93.4.198', 27017)
 
#  Select database 
db = conn['db1']
 
# 选择表
posts = db['posts']
 
post_data = {
  'name': 'alex',
  'age': 18
}
 
#  Insert data into the table 
# result = posts.insert_one(post_data)
 
#  To obtain 1 The data 
# row = posts.find_one()
# print(row)
 
# #  Multiple data acquisition 
# rows = posts.find()
# for row in rows:
#   print(row)
 
#  Delete multiple data 
# rows = posts.delete_many(filter={})
# print(rows)
 
#  Update multiple data 
# posts.update({}, {'name': 'wupeiqi'}) 
sqlalchemy
#!/usr/bin/env python
# -*- coding:utf-8 -
import redis
from flask import Flask, session
from flask_session import Session as FSession
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.debug = True
app.secret_key = 'xxxx'
 
#  Set up the database link 
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123@127.0.0.1:3306/fssa?charset=utf8'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
 
#  instantiation SQLAlchemy
db = SQLAlchemy(app)

app.config['SESSION_TYPE'] = 'sqlalchemy' # session A type of sqlalchemy
app.config['SESSION_SQLALCHEMY'] = db # SQLAlchemy object 
app.config['SESSION_SQLALCHEMY_TABLE'] = 'session' # session The name of the table to save 
app.config['SESSION_PERMANENT'] = True #  If I set it to True , close the browser session Is failure. 
app.config['SESSION_USE_SIGNER'] = False #  Whether to send the pair to the browser session the cookie Value encrypted 
app.config['SESSION_KEY_PREFIX'] = 'session:' #  Save to session The prefix of the value in 
FSession(app)

@app.route('/index')
def index():
 
  session['k1'] = 'v1'
  session['k2'] = 'v1'
 
  return 'xx' 
 
if __name__ == '__main__':
  app.run()

PS: After writing the code, don't rush to run, you need to enter the terminal to execute 1 command to create the database table:


bogon:pro-flask wupeiqi$ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from app import db
>>> db.create_all()
>>> 

Related articles: