Python FastAPI是否支持带有嵌套结构(如yaml)的配置文件?

Python FastAPI是否支持带有嵌套结构(如yaml)的配置文件?,python,fastapi,pyyaml,Python,Fastapi,Pyyaml,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(h

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']
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']
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 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']
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()
作为依赖项传递