boodebr A little library from boodebr.org


Recently Edited
boodebr.config edit
frank, 03 August 2008 (created 11 November 2007)
Tags: config
boodebr.config provides configuration files in the spirit of .INI files, but using either JSON or XML. It provides a more flexible and easier to use API than Much more flexible and easier to use than ConfigParser

The main entry point is the configfile factory function:
cfg = configfile(filename, format='json', allow_dict=False)


Where:
filename
Configuration filename (does not have to exist). Guarantees not to create the file until you add data.
format
'json' or 'xml' (will be autodetected when reading; this specifies the format to write).
allow_dict
True/False - should set() allow you to pass a dict? (The downside of setting this to 'True' is a larger/more verbose configuration file, so only use this you really need it.)
Returns a configuration object.

You get and set data with simple path:key pairs. Here is a short example that demonstrates the API:
from boodebr.config import configfile

# a test object -- subtlety here, must define before calling 'configfile()'
# since it will immediately try to deserialize the configfile (if it exists)
class Foo(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

# create config file in JSON format
cfg = configfile('test.json', 'json')

# first, use the typesafe setters
cfg.set_int('/Root/PathA', 'loops', 100)
cfg.set_float('/Root/PathB', 'a_pct', 0.25)
cfg.set_str('/Root/A/B/C', 'name', 'FooBar')
cfg.set_bool('/Root/A/B', 'run', False)
cfg.set_list('/Root/A', 'a_list', [1, 2.3, 'abc'])

# or, can just set arbitrary objects
f = Foo((1,2,3), ['456', 'xyz'])
cfg.set('/Root/PathC', 'an_object', f)

# reload first with typesafe getters - the final arg 
# is the default value
print "Loops", cfg.get_int('/Root/PathA', 'loops', None)
print "a_pct", cfg.get_float('/Root/PathB', 'a_pct', None)
print "name", cfg.get_str('/Root/A/B/C', 'name', None)
print "do_run", cfg.get_bool('/Root/A/B', 'do_run', None)
print "a_list", cfg.get_list('/Root/A', 'a_list', None)

# now, any object
f = cfg.get('/Root/PathC', 'an_object', None)
print "Foo.a, Foo.b",f.a,f.b

# loading non-existant values will return the default values
print "Expect 'aaa':", cfg.get_str('/Root/NoPath', 'a_value', 'aaa')
print "Expect 54321:", cfg.get_int('/Root/PathA', 'NoSuchValue', 54321)


Now you can examine test.json to see the results. Try passing 'xml' instead of 'json' to configfile() to see the difference.

blog comments powered by Disqus