Created
October 11, 2012 12:17
-
-
Save digulla/3871952 to your computer and use it in GitHub Desktop.
Comfortable config access with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import ConfigParser | |
import inspect | |
class DBConfig: | |
__doc__ = 'Collect a couple of config options in a type' | |
def __init__(self): | |
self.host = 'localhost' # You can also assign default values | |
self.dbname = None | |
def foo(self): pass | |
class ConfigProvider: | |
__doc__ = 'Interface which can copy values from ConfigParser into a config object' | |
def __init__(self, cfg): | |
self.cfg = cfg | |
def update(self, section, cfg): | |
__doc__ = 'Updates values in cfg with values from ConfigParser' | |
for name, value in inspect.getmembers(cfg): | |
if name[0:2] == '__' or inspect.ismethod(value): | |
continue | |
#print name | |
if self.cfg.has_option(section, name): | |
setattr(cfg, name, self.cfg.get(section, name)) | |
class Main: | |
def __init__(self, dbConfig): | |
self.dbConfig = dbConfig | |
def run_me(self): | |
# And presto, we have a comfortable way to access config options | |
print('Connecting to %s:%s...' % (self.dbConfig.host, self.dbConfig.dbname)) | |
# Create demo config | |
config = ConfigParser.RawConfigParser() | |
config.add_section('Demo') | |
#config.set('Demo', 'host', 'domain.com') | |
config.set('Demo', 'dbname', 'sample') | |
configProvider = ConfigProvider(config) | |
dbConfig = DBConfig() | |
# Magic happens here | |
configProvider.update('Demo', dbConfig) | |
main = Main(dbConfig) | |
main.run_me() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment