Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Make database connections using configuration file in complex wsgi ap…

…plication.
  • Loading branch information...
commit 1636e1784a567b1fd45d27c7470f6f134a1ebabc 1 parent 683b149
@GrAndSE authored
View
2  lighty/commands.py
@@ -62,7 +62,7 @@ def parse_args(command_arg_type=None, args=default_args):
parser, args = parse_args()
try:
settings = Settings(args['config'])
- commands = load_commands(settings.section('APPS'))
+ commands = load_commands(settings.section_options('APPS'))
except Exception as e:
print_func(e)
print_func(parser.help_text())
View
75 lighty/conf.py
@@ -19,8 +19,9 @@ class Settings(collections.Mapping):
'''Get settings for class
'''
__slots__ = ('__init__', '__contains__', '__getattr__', '__getitem__',
- '__eq__', '__iter__', '__len__', '__ne__', 'configs', 'get',
- 'items', 'keys', 'section', 'sections', 'settings', 'values')
+ '__eq__', '__iter__', '__len__', '__ne__', '_sections',
+ '_settings', 'get', 'items', 'keys', 'section', 'sections',
+ 'values', )
def __init__(self, main_config, defaults={}):
'''Load main config, parse it and then trying to load applications from
@@ -44,13 +45,13 @@ def __init__(self, main_config, defaults={}):
conf_list.append([main_config])
conf_list.append(parser.options('CONFS'))
# Fill dictionaries
- self.configs = parser.read(itertools.chain(*conf_list))
- self.sections = {}
- self.settings = {}
+ parser.read(itertools.chain(*conf_list))
+ self._sections = {}
+ self._settings = {}
for section in parser.sections():
- self.sections[section] = dict([(name, parser.get(section, name))
- for name in parser.options(section)])
- self.settings.update(self.sections[section])
+ self._sections[section] = dict([(name, parser.get(section, name))
+ for name in parser.options(section)])
+ self._settings.update(self._sections[section])
def __getitem__(self, name):
'''Get value from configuration with specified name
@@ -67,11 +68,11 @@ def __getitem__(self, name):
configuration files
'''
name = name.lower()
- if name in self.settings:
- return self.settings[name]
- for section_name in self.sections:
- if name in self.sections[section_name]:
- return self.sections[section_name][name]
+ if name in self._settings:
+ return self._settings[name]
+ for section_name in self._sections:
+ if name in self._sections[section_name]:
+ return self._sections[section_name][name]
raise KeyError('"%s" not found in configuration' % name)
__getattr__ = __getitem__
@@ -87,20 +88,39 @@ def get(self, name, section=None):
'''
name = name.lower()
if section is None:
- if name in self.settings:
- return self.settings[name]
+ if name in self._settings:
+ return self._settings[name]
else:
- if section in self.sections and name in self.sections[section]:
- return self.sections[section][name]
+ if section in self._sections and name in self._sections[section]:
+ return self._sections[section][name]
else:
raise KeyError('No section "%s" in configuration' % section)
raise KeyError('"%s" not found in configuration' % name)
- def section(self, section):
+ def section_options(self, section):
'''Get all keys from section
+
+ Args:
+ section - section name
+
+ Returns:
+ dictionary contains all the settings names from section
'''
- if section in self.sections:
- return dict_keys(self.sections[section].keys())
+ if section in self._sections:
+ return dict_keys(self._sections[section].keys())
+ raise KeyError('No section "%s" in configuration' % section)
+
+ def section(self, section):
+ '''Get the dictionary of keys and values from section
+
+ Args:
+ section - section name
+
+ Returns:
+ dictionary contains all the settings from sections
+ '''
+ if section in self._sections:
+ return self._sections[section].copy()
raise KeyError('No section "%s" in configuration' % section)
def has_section(self, section):
@@ -112,24 +132,29 @@ def has_section(self, section):
Returns:
True if section exists or False if not
'''
- return section in self.sections
+ return section in self._sections
+
+ def sections(self):
+ '''Get a section names list
+ '''
+ return self._sections.keys()
def __iter__(self):
'''Get iterator over the settings keys
'''
- return self.settings.__iter__()
+ return self._settings.__iter__()
def __len__(self):
'''Get number of unique configuration keys
'''
- return len(self.settings)
+ return len(self._settings)
def keys(self):
'''Get unique configuration options names
'''
- return self.settings.keys()
+ return self._settings.keys()
def values(self):
'''Get all the configuration options values
'''
- return self.settings.values()
+ return self._settings.values()
View
10 lighty/db/backend.py
@@ -11,7 +11,7 @@ class Datastore(object):
'''
__slots__ = ('name', 'db_name', 'db', 'get', 'put', )
- def __init__(self, name, db_name):
+ def __init__(self, name, db_name, **kwargs):
from pymongo import Connection
connection = Connection()
self.name = name
@@ -114,12 +114,12 @@ def __init__(self, default_name='default'):
self.datastores = {}
self.default_name = default_name
- def connect(self, name, db_name=None, **kwargs):
+ def connect(self, name, **kwargs):
'''Create a connection to database
'''
- if not db_name:
- db_name = name
- datastore = Datastore(name, db_name, **kwargs)
+ if 'db_name' not in kwargs:
+ kwargs['db_name'] = name
+ datastore = Datastore(name, **kwargs)
self.datastores[name] = datastore
return datastore
View
15 lighty/wsgi/__init__.py
@@ -24,6 +24,7 @@ class ComplexApplication(BaseApplication):
def __init__(self, settings):
super(ComplexApplication, self).__init__(settings)
+ # process an applications and get a template directories
apps = settings.section('APPS')
template_dirs = []
for app in apps:
@@ -31,12 +32,18 @@ def __init__(self, settings):
template_dir = os.path.join(module.__path__[0], 'templates')
if os.path.exists(template_dir):
template_dirs.append(template_dir)
- try:
- template_dirs += settings.section('TEMPLATE_DIRS')
- except:
- pass
+ # get template directories from settings
+ if settings.has_section('TEMPLATE_DIRS'):
+ template_dirs += settings.section_options('TEMPLATE_DIRS')
self.template_loader = FSLoader(template_dirs)
self.get_template = self.template_loader.get_template
+ # get databse connections
+ from ..db.backend import manager
+ for section in settings.sections():
+ if section.startswith('DATABASE:'):
+ name = section.replace('DATABASE:', '')
+ args = settings.section(section)
+ manager.connect(name, **args)
def WSGIApplication(app_settings):
View
16 tests/conf.py
@@ -17,8 +17,8 @@ def setUp(self):
def testGetFromMainConf(self):
'''Test getting options from main config file'''
- assert self.settings.value == 'test', (
- 'Get returns wrong value %s except test' % self.settings.value)
+ assert self.settings.value == 'test', ('Get returns wrong value %s '
+ 'except test' % self.settings.value)
assert self.settings.value == self.settings.get('value'), (
'__getitem__ and get returns different values')
assert self.settings.VALUE == 'test', 'Lower case error'
@@ -43,16 +43,16 @@ def testAppLoaded(self):
def testSections(self):
'''Test is all values in sections'''
apps_req = TEST_APPS
- apps = sorted(self.settings.section('APPS'))
+ apps = sorted(self.settings.section_options('APPS'))
assert apps == apps_req, ('APPS section was not loaded properly: %s' %
apps)
- assert self.settings.section('APP1') == ['app_var'], (
+ assert self.settings.section_options('APP1') == ['app_var'], (
'APP1 section was not loaded properly: %s' %
- self.settings.section('APP1'))
- assert self.settings.section('APP2') == ['app_var'], (
+ self.settings.section_options('APP1'))
+ assert self.settings.section_options('APP2') == ['app_var'], (
'APP2 section was not loaded properly: %s' %
- self.settings.section('APP1'))
- assert sorted(self.settings.section('CONFS')) == [
+ self.settings.section_options('APP1'))
+ assert sorted(self.settings.section_options('CONFS')) == [
'tests/conf/app1.cfg', 'tests/conf/app2.cfg'], (
'CONFS section was not loaded properly')

0 comments on commit 1636e17

Please sign in to comment.
Something went wrong with that request. Please try again.