首页 > 其他分享 >Store config in the environment

Store config in the environment

时间:2023-11-04 23:44:26浏览次数:46  
标签:dsn str settings Settings environment env config Store

Store config in the environment

https://12factor.net/config

The twelve-factor app stores config in environment variables (often shortened to env vars or env). Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard.

 

pydantic_settings

https://fastapi.tiangolo.com/advanced/settings/#reading-a-env-file

fastapi推荐

 

https://docs.pydantic.dev/latest/concepts/pydantic_settings/#usage

from typing import Any, Callable, Set

from pydantic import (
    AliasChoices,
    AmqpDsn,
    BaseModel,
    Field,
    ImportString,
    PostgresDsn,
    RedisDsn,
)

from pydantic_settings import BaseSettings, SettingsConfigDict


class SubModel(BaseModel):
    foo: str = 'bar'
    apple: int = 1


class Settings(BaseSettings):
    auth_key: str = Field(validation_alias='my_auth_key')  

    api_key: str = Field(alias='my_api_key')  

    redis_dsn: RedisDsn = Field(
        'redis://user:pass@localhost:6379/1',
        validation_alias=AliasChoices('service_redis_dsn', 'redis_url'),  (3)
    )
    pg_dsn: PostgresDsn = 'postgres://user:pass@localhost:5432/foobar'
    amqp_dsn: AmqpDsn = 'amqp://user:pass@localhost:5672/'

    special_function: ImportString[Callable[[Any], Any]] = 'math.cos'  (4)

    # to override domains:
    # export my_prefix_domains='["foo.com", "bar.com"]'
    domains: Set[str] = set()

    # to override more_settings:
    # export my_prefix_more_settings='{"foo": "x", "apple": 1}'
    more_settings: SubModel = SubModel()

    model_config = SettingsConfigDict(env_prefix='my_prefix_')  (5)


print(Settings().model_dump())
"""
{
    'auth_key': 'xxx',
    'api_key': 'xxx',
    'redis_dsn': Url('redis://user:pass@localhost:6379/1'),
    'pg_dsn': MultiHostUrl('postgres://user:pass@localhost:5432/foobar'),
    'amqp_dsn': Url('amqp://user:pass@localhost:5672/'),
    'special_function': math.cos,
    'domains': set(),
    'more_settings': {'foo': 'bar', 'apple': 1},
}
"""

 

使用.env覆盖默认值, 但是最终环境会覆盖.env值

from pydantic_settings import BaseSettings, SettingsConfigDict

'''
default -> env file -> env variable
'''
class Settings(BaseSettings):
    PATH: str = "Awesome API"
    USER: str = "xxx"
    TEST: str = "yyy"

    model_config = SettingsConfigDict(env_file=".env")

if __name__ == "__main__":
    src.machine_learning_workflow_pipeline()

    print("---------------------------")
    print(Settings().PATH)
    print(Settings().USER)
    print(Settings().TEST)

dynaconf

https://www.dynaconf.com/#reading-settings-from-files

Features

  • Inspired by the 12-factor application guide
  • Settings management (default values, validation, parsing, templating)
  • Protection of sensitive information (passwords/tokens)
  • Multiple file formats toml|yaml|json|ini|py and also customizable loaders.
  • Full support for environment variables to override existing settings (dotenv support included).
  • Optional layered system for multi environments [default, development, testing, production] (also called multi profiles)
  • Built-in support for Hashicorp Vault and Redis as settings and secrets storage.
  • Built-in extensions for Django and Flask web frameworks.
  • CLI for common operations such as init, list, write, validate, export.

 

标签:dsn,str,settings,Settings,environment,env,config,Store
From: https://www.cnblogs.com/lightsong/p/17810070.html

相关文章

  • Pset_EnvironmentalImpactValues
    Pset_EnvironmentalImpactValues环境影响值:以下属性捕获元素的环境影响值。它们对应于Pset_EnvironmentalImpactIndicators中定义的指标。环境影响值是将单位指标值乘以元素的相关数量得出的。  NameTypeDescriptionTotalPrimaryEnergyConsumptionP_SINGLEVALUE / If......
  • Viper —— configuration solution for Go
    1.supportseveralformatsofconfigurationconfig.yamlname:'bobby'port:12334main.gotoquickstart packagemainimport("fmt""github.com/spf13/viper")typeServerConfigstruct{ServiceNamestring......
  • 文件名: ?Ciwindows\system32 inetsrconfiglapplicationHost.config 错误:无法写入配
    出现原因:出现这个问题,一般是在程序运行的时候更新程序,导致的.解决方案:MicrosoftWindows[版本6.3.9600](c)2013MicrosoftCorporation。保留所有权利。C:\Users\Administrator>netstopiisadmin/yIISAdminService服务正在停止....IISAdminService服务已成功停......
  • 【zabbix】configure: error: Unable to use libevent (libevent check failed)解决方
    安装zabbix,在zabbix目录下执行编译命令时报错configure:error:Unabletouselibevent(libeventcheckfailed),如图:说明:新服务器,一般依赖不足,需要视情况安装依赖,问题解决。解决方案:yuminstalllibevent-devel-y......
  • zabbix4.x安装出现“configure: error: Not found mysqlclient library”的解决办法
    一、zabbix3.x安装出现“configure:error:Notfoundmysqlclientlibrary”的解决办法1、编译安装zabbix-server出现编译时加参数:--with-mysql在编译时,可能会出现题目中所示的错误,可以通过安装mysql-devel这个库解决:yuminstall mysql-devel-y注:如果出现“......
  • mongo备份篇 mongoexport、mongoimport 以及mongodump、mongorestore
    系列导航一、linux单机版mongo安装(带密码验证)二、mongo集群搭建三、java连接mongo数据库四、java对mongo数据库增删改查操作五、mongo备份篇mongoexport、mongoimport以及mongodump、mongorestore如下是总结mongo数据库在执行备份和恢复中一些常用的语句。备份方面比较:1......
  • nebula-br local-store 模式,快速搭建主备集群实践
    因为线上图数据库目前为单集群,数据量比较大,有以下缺点:单点风险,一旦集群崩溃或者因为某些查询拖垮整个集群,就会导致所有图操作受影响很多优化类但会影响读写的操作不好执行,比如:compact、balanceleader等;双集群在升级的时候也非常有优势,完全可以做到不影响业务运行,比如先升级......
  • vue vue.config.js 配置
    1.开启sourceMap//显示sourceMap,便于调试 //process.env.NODE_ENV有的是dev/prod,有的是development/production,需要自己确认下productionSourceMap:process.env.NODE_ENV!=='production',......
  • Your shell has not been properly configured to use 'conda activate'.
     #./condaactivatepy38CommandNotFoundError:Yourshellhasnotbeenproperlyconfiguredtouse'condaactivate'.Toinitializeyourshell,run   $condainit<SHELL_NAME>Currentlysupportedshellsare: -bash -fish -tcsh -xonsh -......
  • in org.springframework.cache.annotation.ProxyCachingConfiguration required a be
    我的项目是springboot项目,在启动过程中报错如何下Parameter0ofmethodcacheAdvisorinorg.springframework.cache.annotation.ProxyCachingConfigurationrequiredabeanoftype'org.springframework.cache.interceptor.CacheOperationSource'thatcouldnotbefound......