Flask系列(八)flask-session組件

1、簡介

flask-session是flask框架的session組件,因爲原來flask內置session使用簽名cookie保存,該組件則將支持session保存到多個地方,如:python

  • redis:保存數據的一種工具,五大類型。非關係型數據庫
  • memcached
  • filesystem
  • mongodb
  • sqlalchmey:那數據存到數據庫表裏面

安裝mysql

pip3 install flask-sessionredis

2、存儲方式

一、redissql

#!/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類型爲redis
app.config['SESSION_PERMANENT'] = False  # 若是設置爲True,則關閉瀏覽器session就失效。
app.config['SESSION_USE_SIGNER'] = False  # 是否對發送到瀏覽器上session的cookie值進行加密
app.config['SESSION_KEY_PREFIX'] = 'session:'  # 保存到session中的值的前綴
app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port='6379', password='123123')  # 用於鏈接redis的配置

Session(app)


@app.route('/index')
def index():
    session['k1'] = 'v1'
    return 'xx'


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

二、memcachedmongodb

#!/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類型爲redis
app.config['SESSION_PERMANENT'] = True # 若是設置爲True,則關閉瀏覽器session就失效。
app.config['SESSION_USE_SIGNER'] = False # 是否對發送到瀏覽器上session的cookie值進行加密
app.config['SESSION_KEY_PREFIX'] = 'session:' # 保存到session中的值的前綴
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類型爲redis
app.config[
    'SESSION_FILE_DIR'] = '/Users/wupeiqi/PycharmProjects/grocery/96.Flask新課程/組件/2.flask-session'  # session類型爲redis
app.config['SESSION_FILE_THRESHOLD'] = 500  # 存儲session的個數若是大於這個值時,就要開始進行刪除了
app.config['SESSION_FILE_MODE'] = 384  # 文件權限類型

app.config['SESSION_PERMANENT'] = True  # 若是設置爲True,則關閉瀏覽器session就失效。
app.config['SESSION_USE_SIGNER'] = False  # 是否對發送到瀏覽器上session的cookie值進行加密
app.config['SESSION_KEY_PREFIX'] = 'session:'  # 保存到session中的值的前綴

Session(app)


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


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

四、mongodbflask

#!/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類型爲redis

app.config['SESSION_MONGODB'] = pymongo.MongoClient()
app.config['SESSION_MONGODB_DB'] = 'mongo的db名稱(數據庫名稱)'
app.config['SESSION_MONGODB_COLLECT'] = 'mongo的collect名稱(表名稱)'

app.config['SESSION_PERMANENT'] = True  # 若是設置爲True,則關閉瀏覽器session就失效。
app.config['SESSION_USE_SIGNER'] = False  # 是否對發送到瀏覽器上session的cookie值進行加密
app.config['SESSION_KEY_PREFIX'] = 'session:'  # 保存到session中的值的前綴

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 -*-
from pymongo import MongoClient

# 建立連接
conn = MongoClient('47.93.4.198', 27017)

# 選擇數據庫
db = conn['db1']

# 選擇表
posts = db['posts']

post_data = {
    'name': 'shuyang',
    'age': 18
}

# 表中插入數據
# result = posts.insert_one(post_data)

# 獲取一條數據
# row = posts.find_one()
# print(row)

# # 獲取多條數據
# rows = posts.find()
# for row in rows:
#     print(row)

# 刪除多條數據
# rows = posts.delete_many(filter={})
# print(rows)

# 更新多條數據
# posts.update({}, {'name': 'shuyang'})

五、sqlalchemycookie

#!/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'

# 設置數據庫連接
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123@127.0.0.1:3306/fssa?charset=utf8'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

# 實例化SQLAlchemy
db = SQLAlchemy(app)



app.config['SESSION_TYPE'] = 'sqlalchemy'  # session類型爲sqlalchemy
app.config['SESSION_SQLALCHEMY'] = db # SQLAlchemy對象
app.config['SESSION_SQLALCHEMY_TABLE'] = 'session' # session要保存的表名稱
app.config['SESSION_PERMANENT'] = True  # 若是設置爲True,則關閉瀏覽器session就失效。
app.config['SESSION_USE_SIGNER'] = False  # 是否對發送到瀏覽器上session的cookie值進行加密
app.config['SESSION_KEY_PREFIX'] = 'session:'  # 保存到session中的值的前綴
FSession(app)


@app.route('/index')
def index():

    session['k1'] = 'v1'
    session['k2'] = 'v1'

    return 'xx'


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

PS: 在寫好代碼後,不要着急運行,須要先執行進入終端執行一條建立數據庫表的命令:session

$ 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()
>>>

應用場景

若是應用程序比較小,就用原生的加密ccokie 保存session(內置)若是應用程序比較大,就用redis(flask-session)
相關文章
相關標籤/搜索