Ale*_*exA 6 python pyyaml fastapi
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']
Run Code Online (Sandbox Code Playgroud)
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']
Run Code Online (Sandbox Code Playgroud)
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']
Run Code Online (Sandbox Code Playgroud)
然后你可以将Settings()你的路由作为依赖项传递。
| 归档时间: |
|
| 查看次数: |
3058 次 |
| 最近记录: |