Flask配置文件和环境变量:配置文件和环境变量的读取与调用

摘要:Flask

设置配置文件settings.py

在项目根目录下创建settings.py构建配置文件,设置开发,测试,生成三套配置,继承一个base配置,指定key字符串选择当下的配置

class BaseConfig(object):
    DIALECT = 'mysql'
    DRIVER = 'pymysql'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = True
    PREFIX = "/PiraScore"
    DEFAULT_CATEGORY = 'ALL'
    RANK_PAGE_NUM = 10
    RANK_MAX_PAGES = 3

class DevelopmentConfig(BaseConfig):
    USERNAME = 'gp'
    PASSWORD = '123456'
    HOST = '192.168.60.2'
    PORT = '3306'
    DATABASE = 'pira'
    DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOST, PORT, DATABASE)
    SQLALCHEMY_DATABASE_URI = DB_URI


class TestingConfig(BaseConfig):
    USERNAME = 'gp'
    PASSWORD = '123456'
    HOST = '192.168.60.2'
    PORT = '3306'
    DATABASE = 'pira'
    DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOST, PORT, DATABASE)
    SQLALCHEMY_DATABASE_URI = DB_URI


class ProductionConfig(BaseConfig):
    USERNAME = 'gp'
    PASSWORD = '123456'
    HOST = '192.168.60.2'
    PORT = '3306'
    DATABASE = 'pira'
    DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOST, PORT, DATABASE)
    SQLALCHEMY_DATABASE_URI = DB_URI


config = {
    'development': DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig
}

设置环境变量.flaskenv

在项目跟目录下创建Flask环境变量文件.flaskenv,写入当下的环境模式为生产,格式为key,value对

# vim .flaskenv
FLASK_CONFIG=production

安装python-dotenv,用来读取.env环境变量文件

pip install python-dotenv

init脚本中手动读取环境变量,使用load_dotenv方法读取环境变量中的key字符串,进一步拿到settings.py中的配置类型

import os

from dotenv import load_dotenv
from flask import Flask

from settings import config

dotenv_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.flaskenv')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)


def create_app(config_name=None):
    if config_name is None:
        config_name = os.getenv('FLASK_CONFIG', 'development')  # production
    app = Flask('pira_score_web')
    app.config.from_object(config[config_name])

使用current_app调用配置

配置文件是在程序实例实在程序实例init.py中读取的,是程序实例独有的,蓝图实例中没有提供,如果要在蓝图中使用配置文件需要调用current_app对象,它是一个表示当前程序实例的代理对象,当某个程序实例被创建并运行时,它会自动指向当前运行的程序实例,并把所有操作都转发到当前的
程序实例 。 比如需要访问配置时调用current_app.config

from flask import Blueprint, current_app

index = Blueprint('index', __name__)

@index.route('/rank', methods=['GET'], endpoint='rank')
def rank():
    prefix = current_app.config['PREFIX']
    return prefix

你可能感兴趣的:(Flask配置文件和环境变量:配置文件和环境变量的读取与调用)