【发布时间】:2021-02-15 07:55:17
【问题描述】:
Python 框架 FastAPI 支持 .env 样式的配置文件。 它是否可以使用更结构化的配置格式,例如 .yaml 到 ini/toml?
【问题讨论】:
Python 框架 FastAPI 支持 .env 样式的配置文件。 它是否可以使用更结构化的配置格式,例如 .yaml 到 ini/toml?
【问题讨论】:
虽然它没有在框架中本地实现,但您可以执行以下操作:
YAML
import os
from pydantic import BaseSettings
import yaml
yaml_settings = dict()
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "settings.yaml")) as f:
yaml_settings.update(yaml.load(f, Loader=yaml.FullLoader))
class Settings(BaseSettings):
setting_1: str = yaml_settings['setting_1']
setting_2: str = yaml_settings['setting_2']
INI
import configparser
import os
from pydantic import BaseSettings
here = os.path.abspath(os.path.dirname(__file__))
config = configparser.ConfigParser()
config.read(os.path.join(here, "settings.ini"))
class Settings(BaseSettings):
setting_1: str = config['dev']['setting_1']
setting_2: str = config['dev']['setting_2']
TOML
import toml
import os
from pydantic import BaseSettings
here = os.path.abspath(os.path.dirname(__file__))
toml_settings = toml.load(os.path.join(here, "settings.toml"))
class Settings(BaseSettings):
setting_1: str = toml_settings['dev']['setting_1']
setting_2: str = toml_settings['dev']['setting_2']
然后你可以在你的路由中传递Settings() 作为依赖。
【讨论】: