python flask 框架读取 .flaskenv 配置方法
方法1:
from dotenv import dotenv_values def index(): config = dotenv_values('.flaskenv') HOST = config.get('MYSQL_HOST') or 'localhost'
方法2:
import os def index(): SITENAME = os.environ.get('SYSTEM_NAME', 'XiaoGuan')
.flaskenv
# Site 配置 SYSTEM_NAME = Back Home # MySql 配置 MYSQL_HOST = 127.0.0.1 # MYSQL_HOST = dbserver MYSQL_PORT = 3306 MYSQL_DATABASE = pear MYSQL_USERNAME = root MYSQL_PASSWORD = 123456
完整列子:
from flask import Blueprint import os from dotenv import dotenv_values backhome_test = Blueprint('backhome_test', __name__, url_prefix='/backhome/test') @backhome_test.route('/') def index(): config = dotenv_values('.flaskenv') HOST = config.get('MYSQL_HOST') or 'localhost' import os SITENAME = os.environ.get('SYSTEM_NAME', 'XiaoGuan') return "这是backhome/test路由"+HOST + '|' + SITENAME