【需求】
使用配置类管理flask管理测试环境,
通过1个参数即可控制Flask是运行develpment环境还是production环境(数据库配置,邮件配置也要根据环境的变化而变化)
【思路】
1.在config.ini中存储所有的配置信息
2.在settings.py通过DdevelopConfig,ProductionConfig类存取不同测试环境 的环境变量值
3.在app.py通过实例化DdevelopConfig或ProductionConfig类,获取这些类中的环境变量的值
在创建Flask对象app之后,通过方法app.config.from_object(obj)将配置信息写入到app.config
这样最终的效果就是:
在创建app时,通过create_app(config_name),即可灵活的切换测试环境
【代码示例】
目录结构:
config.ini
# Flask对象配置
[app]
FLASK_CONFIG=production
JSON_AS_ASCII =False
JSONIFY_MIMETYPE = "application/json;charset=utf-8"
SECRET_KEY=‘secret string‘
# 数据库配置
[sqlalchemy]
SQLALCHEMY_TRACK_MODIFICATIONS=False
# 线上环境
[production]
DATABASE_URL =‘mysql+mysqlconnector://username:password@ip:port/dbname?charset=utf8‘
# 开发环境
[development]
DATABASE_URL =‘mysql+mysqlconnector://username:password@ip:port/dbname?charset=utf8‘
# 邮件配置信息
[email]
MAIL_SERVER="smtp.126.com"
MAIL_USERNAME=‘xxxx@126.com‘
MAIL_PASSWORD="授权码"
settings.py
import os
from configparser import ConfigParser
basedir = os.path.abspath(os.path.dirname(__file__))
cfgpath = os.path.join(basedir, ‘config.ini‘)
cf = ConfigParser()
cf.read(cfgpath)
# 获取邮件配置
def get_email_config(option):
return cf.get(‘email‘, option)
# 获取邮件配置
def get_app_config(option):
return cf.get(‘app‘, option)
# 获取数据库配置
def get_sqlalchemy_config(option):
return cf.get(‘sqlalchemy‘, option)
# 获取生产环境配置
def get_production_config(option):
return cf.get(‘production‘, option)
# 获取开发环境配置
def get_development_config(option):
return cf.get(‘development‘, option)
class BaseConfig(object):
SECRET_KEY = get_app_config(‘SECRET_KEY‘)
SQLALCHMEY_TRACK_MODIFICATIONS = False
MAIL_SERVER = get_email_config(‘MAIL_SERVER‘)
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USERNAME = get_email_config(‘MAIL_USERNAME‘)
MAIL_PASSWORD = get_email_config(‘MAIL_USERNAME‘)
MAIL_DEFAULT_SENDER = (‘Bluelog Admin‘, MAIL_USERNAME)
class DevelopmentConfig(BaseConfig):
FLASK_ENV = ‘development‘
AAA = ‘in DevelopmentConfig‘
SQLALCHEMY_DATABASE_URI = get_development_config(‘DATABASE_URL‘)
class ProductingConfig(BaseConfig):
FLASK_ENV = ‘production‘
AAA=‘in ProductingConfig‘
SQLALCHEMY_DATABASE_URI = get_production_config(‘DATABASE_URL‘)
config = {
‘production‘: ProductingConfig,
‘development‘: DevelopmentConfig
}
app.py
from flask import Flask
from settings import config,get_app_config
def create_app(config_name=None):
# 不指定config_name,默认取配置文件FLASK_CONFIG的值
# 指定config_name,则以指定的环境为主
if config_name is None:
config_name=get_app_config(‘FLASK_CONFIG‘)
app = Flask(__name__)
cfobj=config[config_name]
app.config.from_object(cfobj)
return app
#测试不指定config_name
app = create_app()
print(app.config[‘FLASK_ENV‘])
print(app.config[‘AAA‘])
print(‘*‘*50)
#测试指定config_name
app = create_app(‘development‘)
print(app.config[‘FLASK_ENV‘])
print(app.config[‘AAA‘])
运行结果:
production
in ProductingConfig
**************************************************
development
in DevelopmentConfig