# -*- coding: utf-8 -*-
# @Time : 2023/9/2
# @Author : 大海
from flask import Flask
class DefaultConfig(object):
"""默认配置"""
MYSQL_HOST = '192.168.66.66'
app = Flask(__name__)
# 设置配置对象方式读取配置
app.config.from_object(DefaultConfig)
@app.route('/')
def index():
# 读取配置,相当于字典中取值
mysql_host = app.config.get('MYSQL_HOST')
# mysql_host = app.config['MYSQL_HOST']
print(mysql_host)
return 'Hello 大海!'
if __name__ == '__main__':
app.run()
# setting.py
# -*- coding: utf-8 -*-
# @Time : 2023/9/2
# @Author : 大海
MYSQL_HOST = '192.168.88.88'
# -*- coding: utf-8 -*-
# @Time : 2023/9/2
# @Author : 大海
from flask import Flask
app = Flask(__name__)
# 设置配置文件方式加载配置
app.config.from_pyfile('setting.py')
@app.route('/')
def index():
# 读取配置,相当于字典中取值
mysql_host = app.config.get('MYSQL_HOST')
# mysql_host = app.config['MYSQL_HOST']
print(mysql_host)
return 'Hello 大海!配置文件方式加载配置。'
if __name__ == '__main__':
app.run()
# export 变量名=配置文件名 Linux系统环境中使用
export PROJECT_SETTING=setting.py
# -*- coding: utf-8 -*-
# @Time : 2023/9/2
# @Author : 大海
from flask import Flask
app = Flask(__name__)
# 设置环境变量方式加载配置
app.config.from_envvar('PROJECT_SETTING', silent=True)
@app.route('/')
def index():
# 读取配置,相当于字典中取值
mysql_host = app.config.get('MYSQL_HOST')
# mysql_host = app.config['MYSQL_HOST']
print(mysql_host)
return 'Hello 大海!环境变量方式加载配置。'
if __name__ == '__main__':
app.run()
silent 参数说明:
- Flase:没找到变量值时,报错通知,默认为Flase
- True:没找到变量值时也正常运行下去
# -*- coding: utf-8 -*-
# @Time : 2023/9/2
# @Author : 大海
from flask import Flask
class DefaultConfig(object):
"""默认配置"""
MYSQL_HOST = '192.168.66.66'
def create_flask_app(config):
app = Flask(__name__)
# 设置配置对象方式读取配置
app.config.from_object(config)
# 设置环境变量方式加载配置
app.config.from_envvar('PROJECT_SETTING', silent=True)
return app
app = create_flask_app(DefaultConfig)
@app.route('/')
def index():
# 读取配置,相当于字典中取值
mysql_host = app.config.get('MYSQL_HOST')
# mysql_host = app.config['MYSQL_HOST']
print(mysql_host)
return 'Hello 大海!'
if __name__ == '__main__':
app.run()