一个固执己见的python模块,用于处理支持外部数据源的配置值。
uplook的Python项目详细描述
什么?
一个固执己见的python模块,用于处理配置值,并支持 外部数据源。
怎么做?
uplook类接受任意数量的键/值。这些变量 作为常规对象属性存储和访问。类型值 <;<;dict>;>;可以以点格式访问。
值也可以是查找函数,方法是使用特殊语法:
+-> The name of the funtion. 1 tilde means the function is a static lookup. | 2 tildes means a lookup is done every time the attribute is accessed. | | +------------+------> An optional pair of values. The first value is the <key> | | | to lookup. The second value is a default value to return | | | in case the key lookup fails. ~~function("key", "default value") | | +-> The default value can also be JSON. In that case you should not use quotes around the value.
实际示例如下:
>>>>u=UpLook(servers='~~consul("first", [])')
为此,您首先需要注册负责 正在检索数据。取决于查找所需值所需的内容 您可以为函数提供一个<;键>;值。
一个(愚蠢的)示例查找函数如下:
defshow_members(cluster_name):ifcluster_name=="first"return["one","two","three"]else:raiseException("Unknown cluster")>>>>u.registerLookup("consul",show_members)
访问值u.value.server将触发注册的lookup 函数并返回其值:
>>>>u.value.servers["one","two","three"]
当注册的函数返回异常时,将返回默认值:
>>>>u=UpLook(servers='~~consul("blahblahblah", [])')>>>>u.value.servers[]
备注
- 当执行查找函数失败且默认值为 已定义,不会引发错误并返回默认值。
- 当执行查找函数失败并且no默认值 定义引发错误。
- 当默认值在单引号或双引号之间时,将返回 真的。当默认值是not在引号之间时,它是 被认为是json。当json无效时,返回一个错误。
更多示例
如果Kwargs可以作为属性访问
>>>>fromuplookimportUpLook>>>>u=UpLook(one=1,two=2)>>>>uUpLook({'two':2,'one':1})>>>>u.value.one1
dict参数值递归映射到属性
>>>>fromuplookimportUpLook>>>>u=UpLook(levels={"level1":{"level2":{"level3":"hello"}}})>>>>uUpLook({'levels':{'level1':{'level2':{'level3':'hello'}}}})>>>>u.value.levels.level1.level2.level3'hello'
在不使用所有助手方法的情况下获取数据部分
>>>>fromuplookimportUpLook>>>>u=UpLook(one=1,two=2)>>>>uUpLook({'two':2,'one':1})>>>>data=u.get()>>>>data.one1
获取数据的简单dict表示
>>>>fromuplookimportUpLook>>>>u=UpLook(one=1,two=2)>>>>uUpLook({'two':2,'one':1})>>>>data=u.dump(){'two':2,'one':1}
在数据容器的键/值对上迭代
>>>>fromuplookimportUpLook>>>>u=UpLook(one=1,two=2)>>>>uUpLook({'two':2,'one':1})>>>>forkey,valueinu.get():....print"key: %s, value: %s"%(key,value)....key:two,value:2key:one,value:1
外部查找值
一些值查找函数
fromuplookimportUpLookfromuplook.errorsimportNoSuchValuedefsomeLookupFunction(key):data={"value.number.one":"hi","value.number.two":"this","value.number.three":"is","value.number.four":"a","value.number.five":"silly","value.number.six":"demo"}try:returndata[key]exceptKeyError:raiseNoSuchValue("%s is an unknown value."%(key))defrandomInt(max):returnrandom.randint(0,max)
使用动态和静态查找初始化uplook实例
>>>instance=UpLook(static='~fubar("value.number.one", "unknown")',>>>dynamic='~~random(100)',>>>normal='hello')
列出所有用户定义的查找函数
>>>forfunctionininstance.listfunctions():printfunctionfubarrandom>>>
寄存器查找函数
>>>instance.registerLookup("fubar",someLookupFunction)>>>instance.registerLookup("random",randomInt)
访问静态查找值
>>>printtest.value.statichi>>>printtest.value.statichi
访问动态查找值
>>>printtest.value.dynamic>>>81>>>printtest.value.dynamic>>>16