On 9 sep, 03:46, maroxe <[email protected]> wrote:
> Hi, I am trying to understand an other magic thing about django: it
> can convert strings to modules. In settings.py, INSTALLED_APPS is
> declared like that:
>
> INSTALLED_APPS = (
> 'django.contrib.auth',
> 'django.contrib.contenttypes',
> 'django.contrib.sessions',
> )
> All it contains is strings. But django will convert those strings to
> modules and import them later.
>
> I want to do be able to do the same thing. but i don't know how.
One of the nice features of OSS is that you can read the source code,
so no need to reinvent the wheel !-)
Here's a snippet from one of our apps that should get you started:
# -*- coding:utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
__backends = dict()
def get_backend(classpath=None):
"""Loads an OAI Repository backend and return an instance of it.
<classpath> is the python qualified path to the backend class, as
a string, ie
'myapp.mymodule.ClassName'
If not provided, the backend specified as OAI_BACKEND in the main
settings
file will be used.
Note : already instanciated backends are served from a local cache
"""
from oai.repository import settings
classpath = classpath or settings.BACKEND
try:
backend = __backends[classpath]
except KeyError:
try:
mod_name, cls_name = classpath.rsplit('.', 1)
mod = import_module(mod_name)
except ImportError, e:
raise ImproperlyConfigured(
'Error importing OAI repository backend module %s:
"%s"' % (mod_name, e)
)
try:
cls = getattr(mod, cls_name)
except AttributeError:
raise ImproperlyConfigured(
'Module "%s" does not define a "%s" class' %
(mod_name, cls_name)
)
# instanciate and stores the backend class
backend = __backends[classpath] = cls()
return backend
#
------------------------------------------------------------------------------
__all__ = ("get_backend",)
HTH
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.