从环境变量声明和加载配置

env_config的Python项目详细描述


声明并从环境变量加载配置。

支持的功能:

  • 为生产、测试和其他环境声明不同的变量集

  • 必要时从文件中加载变量

  • 将配置解析为不同的数据类型

    • str公司
    • 内景
    • 浮动
    • bool('true','false',1,0,'yes','no')
    • str[]
    • 内景[]
    • 浮动[]
    • 布尔[]
    • 嵌套类型
  • 易于处理有关丢失变量和声明问题的报告

    Missingenvironmentvariables:exportERR_KEY_1=[yourvaluehere]exportERR_KEY_1_DICT2_DICT3_KEY4=[yourvaluehere]exportERR_KEY_1_DICT2_KEY3=[yourvaluehere]Missingdeclarations:declare("undeclared",[yourdefinitionhere])Parseerrors:ERR_KEY_1_VALUE1:invalidliteralforint()withbase10:'some int value'

安装

pip install config

示例

创建新的配置实例

fromenv_configimport# control error reporting.# If deferred, config errors are raised the first time Config.get() is called.# The error message contains a detailed report about all errors encountered while parsing config variables.# If not deferred, Config raises on the first error encountered. This most likely happens while calling Config.declare().# Default is defer_raise=Truecfg=Config(defer_raise=False)# load config from a file. See a more detailed example further down.cfg=Config(filename_variable='CONFIG_FILE')

配置日志级别

env_config有一个简单的机制来设置python日志的日志级别,包括所有配置的日志记录器。 库搜索根据此架构生成的环境变量: 日志级别{logger@name.upper} 如果找到,每个变量的值将作为相应记录器的日志级别应用。 环境变量LOG LEVEL(不带记录器名称)设置根记录器的日志级别

可用值为: -调试 -信息 -警告 -错误 -关键的

importosfromenv_configimportos.environ['LOG_LEVEL']='info'# set the root logger to logging.INFOos.environ['LOG_LEVEL_URLLIB3']='critical'# set the urllib3 logger to logging.CRITICALos.environ['LOG_LEVEL_PARAMIKO.TRANSPORT']='debug'# set paramiko.transport to logging.DEBUGcfg=Config()cfg.apply_log_levels()# read the environment variables and apply to the respective log levels

声明并加载标量值

fromenv_configimportConfig,parse_int,parse_float,parse_str,parse_boolcfg=Config()# declare variables with the appropriate parsercfg.declare('my_int_variable',parse_int())cfg.declare('my_float_variable',parse_float())cfg.declare('my_str_variable',parse_str())cfg.declare('my_bool_variable',parse_bool())# load the values# will load the value of MY_INT_VARIABLE as an intint_result=cfg.get('my_int_variable')# will load the value of MY_FLOAT_VARIABLE as a floatfloat_result=cfg.get('my_float_variable')# will load the value of MY_STR_VARIABLE as a strstr_result=cfg.get('my_str_variable')

声明并加载列表值

fromenv_configimportConfig,parse_int_listcfg=Config()# declare variables with the appropriate parsercfg.declare('my_int_list_variable',parse_int_list())# load the values# will load the value of MY_INT_LIST_VARIABLE as a list of ints.# By default it assumes the elements to be comma separatedint_list_result=cfg.get('my_int_list_variable')

声明并加载嵌套值

大多数库需要多个变量才能正确配置。 嵌套值有助于减少将配置与库关联所需的样板文件

fromenv_configimportConfig,parse_strimportpsycopg2cfg=Config()cfg.declare('database',{'dbname':parse_str(),'user':parse_str(),'password':parse_str()},)# this will load values from these environment variables and parse them into a dict:#  - DATABASE_DBNAME#  - DATABASE_USER#  - DATABASE_PASSWORDpsyco_config=cfg.get('database')# the dict will look like this: {'dbname': 'some value', 'user': 'username', 'password': 'vsjkfl'}psyco_connection=psycopg2.connect(**psyco_config)

命名变量

fromenv_configimportConfig,parse_strimportpsycopg2cfg=Config(namespace='my_prefix')cfg.declare('database')# the value will be loaded from the environment variable: MY_PREFIX_DATABASEvalue=cfg.get('database')

添加验证

fromenv_configimportConfig,parse_str,parse_str_listfromvalidatorsimportemail# config expects validators to raise an Error on failure.# Since the validators package returns Failures instead of raising, we create a small adapter.defemail_validator(value):result=email(value)ifisinstance(result,ValidationFailure):raiseValueError('"{}" is not a valid email address'.format(value))cfg=Config()cfg.declare('valid_email',parse_str(validator=email_validator))# this also works with lists. The validator function is applied to each value separatelycfg.declare('valid_list_of_emails, parse_str_list(validator=email_validator))valid_email=cfg.get('valid_email')valid_list_of_emails=cfg.get('valid_list_of_emails')

在运行时重新加载配置

fromenv_configimportConfig,parse_str,reloadcfg=Config()cfg.declare('some_value',parse_str())value=cfg.get('some_value')# Values are actually loaded during declare().# Changes to the environment at runtime are not picked up automatically.# Relaoding has to be triggered explicitly.cfg.reload()new_value=cfg.get('some_value')

声明可选变量

有时您只想加载所有变量的子集。例如,现在大多数应用程序都是执行的 在实时环境和测试环境中。 另一个例子是不同的进程,例如web端点和后台工作进程,共享配置设置

# config.pyfromenv_configimportConfig,parse_strdefdeclare_config(tag):required=('live','test')test_optional=('live',)cfg=Config()# this variable is available both in live and testcfg.declare('some_value',parse_str(),required,tag)# this variable is only available in live. In test it won't be loaded and only raises an error when accessed.cfg.declare('some_other_value',parse_str(),test_optional,tag)returncfg
# live-app.pyfromconfigimportdeclare_config# the active tag is 'live', so all variables tagged with 'live' are required and raise errors when missing.cfg=declare_config('live')# access variablesval=cfg.get('some_value')
# something_test.pyfromconfigimportdeclare_config# the active tag is 'test', so all variables tagged with 'test' are required and raise errors when missing.# All other variables become optional and only raise errors when accessed withcfg.declare_config('test')# access variablesval=cfg.get('some_value')# raise an error, because the variable is not available in 'test'val2=cfg.get('some_other_value')

从文件加载变量

有时显式地声明所有变量是相当麻烦的。 例如,PyCharm变量声明很难使用

为了优雅地处理这些情况,可以从bash文件加载声明为标记的变量。 所以只需要声明一个变量(文件名)。其余的是从那个文件加载的。 但该文件未计算。只有export声明被提取并解析为变量

定义保存文件名的变量

exportCONFIG_FILE=test.sh

使用变量声明创建文件test.sh。

#!/usr/bin/env bash
# comment is ignored
HIDDEN_VARIABLE="value not parsed"exportVISIBLE_VARIABLE_1="this value will be available"function{# if the line does not start with export it's ignored
}# variables inside strings are not expanded. The value will contain the literal :code:`$OTHER_VARIABLE`.
exportVARIABLE_CONTAINING_REFERENCE="$OTHER_VARIABLE"

然后设置CONFIG_FILE变量以加载文件

fromenv_configimportConfig,parse_str# uses the value of CONFIG_FILE as the file name to load variables fromconfig=Config(filename_variable='CONFIG_FILE',defer_raise=False)# visible_variable_1 is declared in test and the current tag is test. variable1 will be loaded from test.shconfig.declare('visible_variable_1',parse_int(),('test',),'test'))# visible_variable_2 is declared in the 'default' tag and not available in the config file.# visible_variable_2 will be ignored because the current tag is 'test'config.declare('visible_variable_1',parse_int(),('default',),'test')

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java为什么加载个人密钥库需要这么多时间?   当我使用main创建Android应用程序UI时,如何通过java修改它。xml文件?   java Tomcat 6和7:WebappClassLoader:尝试为名称org/apache/openjpa/persistence/osgi/BundleUtils复制类定义   java`parseInt()`和`parseDouble()`throw`NumberFormatExeption`   JavaSpringMongoDB填充引用   在LinuxMint中打开Eclipse时发生java错误;OpenJDK 64位服务器VM警告:忽略选项MaxPermSize=512m;支持在8.0中被删除   使用PKCS7Padding的AES CBC加密在Java和Objective中有不同的结果   java为什么Jackson要用一个以类命名的额外层来包装我的对象?   json在Java中使用parallelStream提取值   JavaSpring存储库自动生成方法:按给定的顶部编号+按字段描述排序选择   java是否有可序列化的标准闭包接口?   .NET与Java在初创公司的web应用程序开发   如何修复java。java中的lang.unsatifiedLinkError   JavaFX+Spring Boot+Hibernate应用程序对多个环境的java支持   自定义视图组中的java更改未呈现