1. 在app.py文件中
from datetime import timedelta
from flask_wtf.csrf import CSRFProtect
from flask import Flask, session
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session
SECRET_KEY = 'fjsiogkgnmdinging'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@localhost:3306/info36'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT)
PERMANENT_SESSION_LIFETIME = timedelta(days=1)
app.config.from_object(Config)
redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT, decode_responses=True)
@app.route('/', methods=['GET', 'POST'])
redis_store.set("name", "laowang")
print(redis_store.get("name"))
session["name"] = "zhangsan"
print(session.get("name"))
if __name__ == '__main__':
2.这样写在一起不方便后续开发,所以进行抽取
1.抽取配置类,将配置信息放入项目根目录下的config.py文件中,然后在导入app.py文件中。
from datetime import timedelta
from redis import StrictRedis
SECRET_KEY = 'fjsiogkgnmdinging'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@localhost:3306/info36'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT)
PERMANENT_SESSION_LIFETIME = timedelta(days=1)
LEVEL_NAME = logging.DEBUG
class DevelopConfig(Config):
class ProductConfig(Config):
class TestConfig(Config):
"develop": DevelopConfig,
"product": ProductConfig,
2.将初始化信息抽取,在项目根目录下创建一个包,此包名与项目名相关。并在init.py文件中将初始化信息放入,主要就是创建一个create_app方法方便调用
from flask_wtf.csrf import CSRFProtect
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session
from config import Config, config_dict
def create_app(config_name):
config = config_dict.get(config_name)
app.config.from_object(config)
log_file(config.LEVEL_NAME)
redis_store = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, decode_responses=True)
def log_file(LEVEL_NAME):
logging.basicConfig(level=LEVEL_NAME)
file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
file_log_handler.setFormatter(formatter)
logging.getLogger().addHandler(file_log_handler)
3.视图函数的抽取,视图函数要放入对应模块中的init文件中,
from flask import Blueprint
index_blue = Blueprint('/index',__name__)
from info.modules.index import view
from info.modules.index import index_blue
@index_blue.route('/', methods=['GET', 'POST'])
from flask_wtf.csrf import CSRFProtect
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session
from config import config_dict
def create_app(config_name):
config = config_dict.get(config_name)
app.config.from_object(config)
redis_store = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, decode_responses=True)
from info.modules.index import index_blue
app.register_blueprint(index_blue)