没有项目描述
python-jsonstore的Python项目详细描述
jsonstore
此模块提供一个类,该类映射来自json文件的键和值。 在它的属性上。
目的是提供一种方便的装载和保存方法 以熟悉的可读格式配置。这是多一点 比灵活 configparser python中包含的模块。
这项工作是在python 2.7+和python 3.3+上测试和工作的。会的 不适用于2.6或更低版本,但预计适用于3.0-3.2版本。测试 由于以下原因,不在3.2.6中工作 mistreating 解析测试代码时的。这也在pypy和pypy3上进行了测试。
示例
基础知识
# by default JsonStore commits on every change unless in a transactionstore=JsonStore('config.json')store.a_string="something"store.a_list=[1,2,3]store.a_dictionary={'dict-list':[{}],'ln(2)':0.69314718056,'for-you':u"?",}# you can use […] to set/get/delete string keysstore['some_key']="a value"# the key is split on '.'s and works on dictionariesdelstore['a_dictionary.dict-list']store['a_dictionary.new_value']="old value"# you can also use the syntactic sugar for tuple keys (explicit lists work too)assertstore['a_dictionary','new_value']=="old value"# you can traverse lists tooassertstore['a_list',-1]==3# you can use slices in listsassertlen(store['a_list',1:])==2# deep copies are made when assigning valuesmy_list=['fun']store.a_list=my_listassertstore.a_listisnotmy_listassert'a_list'instore# deep copies are also returned to avoid unsanitary changes being madestore.a_dictionary['new_value']="new value"# won't update the store!assertstore.a_dictionary['new_value']=="old value"assertstore.a_dictionaryisnotstore.a_dictionary
交易
JsonStore对象可以用作context managers来提供 在发生异常时回滚的事务。这个 事务模型是原始的;您只能嵌套事务。
当将存储放入事务中时,它不会将更改保存到 在所有交易结束前归档。
fromjsonstoreimportJsonStore# even with auto_commit=True, the file won't be saved until the last contexts has been closedwithJsonStore('config.json',indent=None,auto_commit=False)asstore:self.value=1# the context manager will roll back changes made if an exception is raisedstore=JsonStore('config.json',indent=None)try:withstore:store.value="new"raiseExceptionexceptException:pass# here we see the value that was saved previouslyassertstore.value==1