Skip to content

Commit

Permalink
added loader module for importing a python class or django model by name
Browse files Browse the repository at this point in the history
  • Loading branch information
trey0 committed Jun 6, 2012
1 parent ab96036 commit 3fb477c
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
29 changes: 29 additions & 0 deletions geocamUtil/loader.py
@@ -0,0 +1,29 @@
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__

"""
Utilities for loading Python classes and Django models by name. Modeled
in part on django.utils.importlib.
"""

def getModClass(name):
"""converts 'app_name.ModelName' to ['stuff.module', 'ClassName']"""
try:
dot = name.rindex('.')
except ValueError:
return name, ''
return name[:dot], name[dot + 1:]


def getModelByName(qualifiedName):
"""
converts 'module_name.ClassName' to a class object
"""
appName, className = qualifiedName.split('.', 1)
modelsName = '%s.models' % appName
__import__(modelsName)
mod = sys.modules[modelsName]
return getattr(mod, className)
31 changes: 31 additions & 0 deletions geocamUtil/storeTest.py
@@ -0,0 +1,31 @@
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__

import shutil

from geocamUtil.store import FileStore, LruCacheStore


class StoreTest(TestCase):
def storeTest(self, storeFactory):
tempDir = tempfile.mkdtemp('-storeTestDir')

store1 = storeFactory(tempDir)
store1['a'] = 1
store1['b'] = 2
store1.sync()

store2 = storeFactory(tempDir)
self.assertEqual(store2['a'], 1)
self.assertEqual(store2['b'], 2)

shutil.rmtree(tempDir)

def test_FileStore(self):
self.storeTest(FileStore)

def test_LruCacheStore(self):
self.storeTest(lambda path: LruCacheStore(FileStore(path), 100))
1 change: 1 addition & 0 deletions geocamUtil/tests.py
Expand Up @@ -14,6 +14,7 @@
from geocamUtil.models.ExtrasFieldTest import ExtrasFieldTest
from geocamUtil.BuilderTest import BuilderTest
from geocamUtil.InstallerTest import InstallerTest
from geocamUtil.storeTest import StoreTest
from geocamUtil.icons.rotateTest import IconsRotateTest
from geocamUtil.icons.svgTest import IconsSvgTest

Expand Down

0 comments on commit 3fb477c

Please sign in to comment.