flask获取配置文件中的数据的不同方法
源码介绍
基本代码
from flask import Flask app = Flask(__name__) app.config.xxxxx # 获取配置信息的不同方法
Flask.config属性
# 这里的 instance_relative_config 是Flask类初始化的一个参数,默认为False
self.config = self.make_config(instance_relative_config)
Flask.make_config(instance_relative_config)方法
def make_config(self, instance_relative=False): """Used to create the config attribute by the Flask constructor. The `instance_relative` parameter is passed in from the constructor of Flask (there named `instance_relative_config`) and indicates if the config should be relative to the instance path or the root path of the application. .. versionadded:: 0.8 """ root_path = self.root_path if instance_relative: root_path = self.instance_path defaults = dict(self.default_config) defaults["ENV"] = get_env() defaults["DEBUG"] = get_debug_flag() return self.config_class(root_path, defaults)
Flask.config_class()方法
config_class = Config
Config类
所以获取配置数据的方法都在这里面,我们可以:
from flask.config import Config
查看里面具体的方法。
具体实例
通过settings.py文件获取 ***
项目是按照“虚拟环境 + flask run方法启动”的。
sayhello/__init__.py中的内容如下:
# -*- coding: utf-8 -*- from flask import Flask from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy app = Flask('sayhello') app.config.from_pyfile('settings.py') # 从settings.py文件中获取配置 app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True db = SQLAlchemy(app) bootstrap = Bootstrap(app) moment = Moment(app) from sayhello import views, errors, commands
settings.py中的内容如下(注意配置信息必须大写!!!)
# -*- coding: utf-8 -*- import os import sys from sayhello import app # SQLite URI compatible WIN = sys.platform.startswith('win') if WIN: prefix = 'sqlite:///' else: prefix = 'sqlite:////' dev_db = prefix + os.path.join(os.path.dirname(app.root_path), 'data') SECRET_KEY = os.getenv('SECRET_KEY', 'secret string') SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URI', dev_db)
使用类组织配置数据 ***
本项目也是通过虚拟环境+flask run命令来启动的。
bluelog/__init__.py中的工厂函数如下:
from bluelog.settings import config basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) def create_app(config_name=None): if config_name is None: config_name = os.getenv('FLASK_CONFIG', 'development') app = Flask('bluelog') app.config.from_object(config[config_name]) register_logging(app) register_extensions(app) register_blueprints(app) register_commands(app) register_errors(app) register_shell_context(app) register_template_context(app) register_request_handlers(app) return app
bluelog/settings.py中的内容如下:
# -*- coding: utf-8 -*- import os import sys basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) # SQLite URI compatible WIN = sys.platform.startswith('win') if WIN: prefix = 'sqlite:///' else: prefix = 'sqlite:////' class BaseConfig(object): SECRET_KEY = os.getenv('SECRET_KEY', 'dev key') DEBUG_TB_INTERCEPT_REDIRECTS = False SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_RECORD_QUERIES = True CKEDITOR_ENABLE_CSRF = True CKEDITOR_FILE_UPLOADER = 'admin.upload_image' MAIL_SERVER = os.getenv('MAIL_SERVER') MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USERNAME = os.getenv('MAIL_USERNAME') MAIL_PASSWORD = os.getenv('MAIL_PASSWORD') MAIL_DEFAULT_SENDER = ('Bluelog Admin', MAIL_USERNAME) BLUELOG_EMAIL = os.getenv('BLUELOG_EMAIL') BLUELOG_POST_PER_PAGE = 10 BLUELOG_MANAGE_POST_PER_PAGE = 15 BLUELOG_COMMENT_PER_PAGE = 15 # ('theme name', 'display name') BLUELOG_THEMES = {'perfect_blue': 'Perfect Blue', 'black_swan': 'Black Swan'} BLUELOG_SLOW_QUERY_THRESHOLD = 1 BLUELOG_UPLOAD_PATH = os.path.join(basedir, 'uploads') BLUELOG_ALLOWED_IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif'] class DevelopmentConfig(BaseConfig): SQLALCHEMY_DATABASE_URI = prefix + os.path.join(basedir, 'data-dev.db') class TestingConfig(BaseConfig): TESTING = True WTF_CSRF_ENABLED = False SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' # in-memory database class ProductionConfig(BaseConfig): SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', prefix + os.path.join(basedir, 'data.db')) config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'production': ProductionConfig }
外面wsgi.py中的内容如下:
import os from dotenv import load_dotenv dotenv_path = os.path.join(os.path.dirname(__file__), '.env') if os.path.exists(dotenv_path): load_dotenv(dotenv_path) from bluelog import create_app # noqa app = create_app('production')
~~~