konf是一个python包,旨在简化配置文件中变量的使用。即时支持json和yaml。

konf的Python项目详细描述


Build Status

konf

用于解决位于VCS之外的Python配置文件问题的小型工具。

安装:

pip install konf

运行测试:

nosetests

为什么是康夫?

有时需要在python代码之外获取一些设置,然后在应用程序中使用它们。这可以是密钥、身份验证令牌、第三方服务的url或其他依赖于服务器的设置。开发人员(或IT工程师)面临几个挑战:

  • 验证从配置导入的数据。它可以是简单的类型,与可能值的范围或正则表达式匹配。
  • 尊重所有设置。检查配置是否包含所有必需的数据。此外,检查配置中是否没有多余的(冗余的)东西也是很有用的(因为它可能是数据,而忘记在应用程序中考虑)。
  • 了解出问题时会发生什么。正确的表示异常允许立即理解(只是查看了日志)问题是什么。在部署服务器时很有用。

特点:

  • 允许干燥导入变量
  • 人类可读性
  • 即时支持json和yaml(事实上,将自动安装其他库来支持它)
  • 输入或验证所有导入数据。这是必需的,因为人为因素预防
  • python 2.7,3+兼容
  • 100%代码覆盖率
  • 可以使用配置文件的自定义格式。如果我错过了,现在除了支持的格式之外,任何人都可以使用其他格式,您可以创建一个关于它的issue,并且可能在下一个版本中将支持新格式。

对于python数据结构,验证使用了优秀的库 kolypto/py-good

对于yaml解析,使用了kirill simonov的一个大库 PyYAML

快速启动

看看密码。

fromkonfimportKonf# Filling of variables from config file tokens.yaml in k_ objectk_=Konf('tokens.yaml')# Getting variables from k_: first argument is a name of variable (specified in the config),# second can be a type or validatorSECRET_KEY=k_('secret_key',basestring)AUTH_TOKEN=k_('auth_token',basestring)# In the next example is used a validator: list, that must contain# only objects with basestring type (str or unicode)CLIENTS=k_('clients',[basestring])# And dict with two required keys with appropriate typesDELAYS=k_('delays',{'case1':int,'case2':int})

您可以在 good 第页

好吧,接下来发生了什么?想象一下tokens.yaml丢失了。在这种情况下,在脚本执行之后,我们可以看到下一条异常消息:

konf.main.ReadError: Can`t access to the configuration file "tokens.yaml"

让我们创建一个文件tokens.yaml并输入next:

---secret_key:FOOauth_token:BARclients:Q,delays:case1:15case2:17

出现异常:

Traceback (most recent call last):
  File "/Users/me/python/examples/example.py", line 19, in <module>CLIENTS=k_('clients',[basestring])
  File "/Users/me/python/examples/konf/konf/main.py", line 126, in __call__raiseself.ValidationError(e)konf.main.ValidationError: expected a list

然后纠正这个错误:

---secret_key:FOOauth_token:BARclients:[Q]delays:case1:15case2:17

现在一切都好了,因为[Q]表示值列表,而不是字符串。note:您可以在本文档页的末尾看到所有支持的异常的列表。

默认值

如果配置文件中不包含任何变量,是否需要使用值?可以使用默认值。

fromkonfimportKonfk_=Konf('extra.yml')# 3rd arg is a default. If variable STRICT is not contained in config file,# USE_STRICT will be FalseUSE_STRICT=k_('STRICT',bool,False)# You can also use None as default valueWINNER=k_('WINNER',int,None)# Default values will never be validated, because you forcibly declaring it.# So, the next example is legit.SHIFT_TIME=k_('SHIFT',int,complex(42,42))

检查冗余变量

有时,您希望确保配置文件中的所有变量都已使用,并且没有忘记任何事情。 在这种情况下,check_redundant()方法可能会有帮助。

fromkonfimportKonfk_=Konf('bar.yaml')FOO1=k_('foo1',int)FOO2=k_('foo2',int)# If config file contains anything except foo1 and foo2,# RedundantConfigError will be raised after call of this method!k_.check_redundant()# Fail

默认值和check_redundant()也可以一起正常工作。

fromkonfimportKonfk_=Konf('foo.yaml')X=k_('X',int,0)Y=k_('Y',int,0)# If X and Y doesn't contained in the config file, RedundantConfigError will not be raised# after next line of code, because they have default values.# So, it's just like X == 0 and Y == 0k_.check_redundant()# Success

更复杂的示例

以可读的形式将内容写入social_auth.yml:

---SN:vk:key:'123'secret:qwertygoogle:key:'456'secret:uioptwitter:key:'789'secret:zxcok:key:'000'secret:vbnpublic_name:m

在settings.py中逐步处理它

# 0. Select configuration filek_=Konf('social_auth.yml')# 1. Declare validators# You can cache validators inside a Konf object as if it's a standard python dictk_['v1']={'key':basestring,'secret':basestring,}k_['v2']={'key':basestring,'secret':basestring,'public_name':basestring}# 2. Get variables from config# For avoid copy-paste and massive chunks of code, just declare a new variable# and pass data from config to itsn=k_('SN',{'vk':k_['v1'],# You can choose validator you want, for example v1...'google':k_['v1'],'twitter':k_['v1'],'ok':k_['v2']# ...or v2})# 3. Fill everything to a python variables which are required for 3rd-party librarySOCIAL_AUTH_VK_OAUTH2_KEY=sn['vk']['key']SOCIAL_AUTH_VK_OAUTH2_SECRET=sn['vk']['secret']SOCIAL_AUTH_GOOGLE_OAUTH2_KEY=sn['google']['key']SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET=sn['google']['secret']SOCIAL_AUTH_TWITTER_KEY=sn['twitter']['key']SOCIAL_AUTH_TWITTER_SECRET=sn['twitter']['secret']SOCIAL_AUTH_ODNOKLASSNIKI_KEY=sn['ok']['key']SOCIAL_AUTH_ODNOKLASSNIKI_SECRET=sn['ok']['secret']SOCIAL_AUTH_ODNOKLASSNIKI_OAUTH2_PUBLIC_NAME=sn['ok']['public_name']# 4. Check that config doesn't contain some garbage# (this might mean you forgot to get these variables, or this config is wrong, some draft for example)k_.check_redundant()# 5. If server is running without errors, and you will meet issue with this 3rd-party library later,# you can be sure that problem isn't in your configuration file.# Otherwise, you'll just catch a error on a start server stage.

支持的异常列表

ExceptionRaises when…
ValidationErrorData from config file doesn’t match to the ^{tt4}$ arg
IncompleteConfigErrorTrying to get variable that not contained in a config file
ReadErrorConfig file can’t be read
ParseErrorThird-party parser can’t parse configuration file
ReassignmentErrorVariable is loaded not for the first time
FileExtensionErrorExtension of the config isn’t supported, and ^{tt5}$ arg isn’t specified
RedundantConfigErrorCall of ^{tt2}$ if any of variables in a config isn’t used in app
ValidatorManagementErrorIncorrect usage of validators

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

推荐PyPI第三方库


热门话题
java如何在mongodb中获取用户有权访问的数据库列表?   基于契约和类不变量的java设计   java我的代码有什么问题,似乎是正确的,但事实并非如此   java Android初学者:布局按钮和文本   400错误Paypal令牌API与Java(HttpURLConnection)   为什么Java从socket中随机读取数据,而不是整个消息?   如果我调用scanner,我会扫描两次。先是下一个,然后是扫描仪。下一个   如果消息发送失败,java ActiveMQ/JMS不重试   java有没有类似于dynaTrace的开源框架?   java Android:获取zip中的文件数(使用存储卷/存储访问框架)   java无法将流图像解码为片段   java如何修复Jenkins插件中的“此位置的预期stackmap帧”   java如何使用javac编译器编译AndroidManifest。xml文件?