flask 如何读取配置文件
时间: 2023-07-18 18:08:15 浏览: 186
在 Flask 中,可以使用 `configparser` 模块读取配置文件。具体步骤如下:
1. 在 Flask 项目的根目录下创建一个名为 `config.ini` 的配置文件,格式为:
```
[DEFAULT]
debug = True
[database]
username = your_username
password = your_password
host = localhost
port = 3306
database = your_database
```
2. 在 Flask 项目中,导入 `configparser` 模块并读取配置文件:
```
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
```
3. 使用 `config` 对象获取配置项的值:
```
debug = config.getboolean('DEFAULT', 'debug')
username = config.get('database', 'username')
password = config.get('database', 'password')
host = config.get('database', 'host')
port = config.getint('database', 'port')
database = config.get('database', 'database')
```
这样就可以通过配置文件来配置 Flask 应用程序了。