配置文件
配置文件的方式有很多,下面介绍两种;
第一种:根据全局变量实现
App.py
from flask import Flask, session
app = Flask(__name__)
# 加载配置文件
app.config.from_object("config.settings")
@app.route("/index")
def index():
session["xx"]=123
return "ok"
if __name__ == '__main__':
app.run()
settings.py
SECRET_KEY = "a1b2c3"
A = 123
# 加载localsettings文件,如果文件存在,那么会读取文件中的配置,如果不存在跳过;适用于生产环境和测试环境配置分隔
try:
from setting_about.config.localsettings import *
except ImportError:
pass
localsettings.py
SECRET_KEY = "xxxxxxx"
第二种:基于类的配置文件
app.py
from flask import Flask, session
app = Flask(__name__)
# 根据不同环境切换不同的配置文件的类
app.config.from_object("config.settings.DevSetting")
# app.config.from_object("config.settings.ProSetting")
@app.route("/index")
def index():
session["xx"]=123
return "ok"
if __name__ == '__main__':
app.run()
settings.py
class BaseSetting(object):
SECRET_KEY = "a1b2c3"
class DevSetting(BaseSetting):
MYSQL_HOST = "172.16.2.12"
class ProSetting(BaseSetting):
MYSQL_HOST = "172.16.1.3"