【问题标题】:Does FastAPI support config files with nested structures like yaml?FastAPI 是否支持带有 yaml 等嵌套结构的配置文件?
【发布时间】:2021-02-15 07:55:17
【问题描述】:

Python 框架 FastAPI 支持 .env 样式的配置文件。 它是否可以使用更结构化的配置格式,例如 .yaml 到 ini/toml?

【问题讨论】:

    标签: python fastapi pyyaml


    【解决方案1】:

    虽然它没有在框架中本地实现,但您可以执行以下操作:

    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() 作为依赖。

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 1970-01-01
      • 2019-03-20
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      相关资源
      最近更新 更多