项目准备:
配置参数
项目配置: 新建工程: 配置虚拟环境: 通过配置类添加配置参数: Debug配置, 初始化数据库对象, Mysql配置及数据库创建 redis配置: 端口6379和域名: 创建存储对象:redis_store = redis.StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT) 添加CSRF配置:CSRFProtect(app) 对数据库有修改的操作:POST,PUT,PATCH,DELETE 设置Session:Session(app) 配置session的参数: from flask-session 保存位置:redis 设置签名:更高级的加密防护, 设置保存的时间:SESSION_PERMANENT=False 设置session的过期时间,默认值是31天 设置session保存的redis的域名和端口 设置secret_key Base64 import base64 base64.b64encode(os.urandom(48)) 测试session:使用redis格式化工具iedis 添加secret_key 导入flask.session 设置session 通过iedis查看session
配置文件:
import redis
from flask import Flask
# Flask参数,可以配置静态文件路由,及文件夹
from flask import session
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.wtf import CSRFProtect
from flask_session import Session
from redis import StrictRedis
app = Flask(__name__)
class Config():
DEBUG=True
SECRET_KEY = '+BYNWiw9WOYHU3qrshRdx5J6aAneDvZcEhJ7+bGApt0ojZDi9rodNJ2fae6VKvVM'
SQLALCHEMY_DATABASE_URI = "mysql://root:mysql@127.0.0.1:3306/NewsDB"
SQLALCHEMY_TRACK_MODIFICATIONS = False
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
# Session保存配置
SESSION_TYPE = "redis"
# 开启session签名
SESSION_USE_SIGNER = True
# 指定 Session 保存的 redis
SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT)
# 设置需要过期
SESSION_PERMANENT = False
# 设置过期时间
PERMANENT_SESSION_LIFETIME = 86400 * 2
app.config.from_object(Config)
db = SQLAlchemy(app)
redis_store = redis.StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT)
CSRFProtect(app)
Session(app)
manager = Manager(app)
Migrate(app,db)
manager.add_command('db',MigrateCommand)
@app.route("/")
def index():
session['name']= 'ITCAST'
return "Welcome to Alice' PKM!"
if __name__ == "__main__":
manager.run()
Flask-script及迁移
manager = Manager(app)
关联app与db:Migrate(app, db)
将迁移命令添加到manager:manager.add_command('db',MigrateCommand)