Source

gnocchi-tools / gnocchi / tools / utils.py

Full commit

from django.utils.importlib import import_module
def autodiscover_factory(module):
    def autodiscover():
        """
        Auto-discover INSTALLED_APPS modules and fail silently when
        not present.
        """
        import imp
        from django.conf import settings

        def import_app(app):
            # For each app, we need to look for an module with the module inside
            # that app's package. We can't use os.path here -- recall that
            # modules may be imported different ways (think zip files) -- so we
            # need to get the app's __path__ and look for admin.py on that path.

            # Step 1: find out the app's __path__ Import errors here will (and
            # should) bubble up, but a missing __path__ (which is legal, but
            # weird) fails silently -- apps that do weird things with __path__
            # might need to manually ensure that the files are being imported.

            try:
                app_path = import_module(app).__path__
            except AttributeError:
                return

            # Step 2: use imp.find_module to find the app's pages_templates.py.
            # For some reason imp.find_module raises ImportError if the app
            # can't be found but doesn't actually try to import the module. So
            # skip this app if its pages_templates.py doesn't exist
            try:
                imp.find_module(module, app_path)
            except ImportError:
                return

            # Step 3: import the app's pages file. If this has errors we want
            # them to bubble up.
            import_module("%s.%s" % (app, module))

        for app in settings.INSTALLED_APPS:
            import_app(app)

    return autodiscover

class ChoicesList(object):
    '''
    A list-like object to make Choices easier to use.
    Construct by passing a list of two-tuples, and get free access to attributes
    on the object for names of the values

    >>> choices = ChoicesList((0, 'First'), (1, 'Second'), (5, 'Something else')
    >>> choices.SECOND
    1
    >>> choice.SOMETHING_ELSE
    5
    >>> list(choices)
    [(0, 'First'), (1, 'Second'), (5, 'Something else')]
    '''
    def __init__(self, *items):
        self.items = items
        for val, label in items:
            setattr(self, label.upper().replace(' ', '_'), val)

    def __iter__(self):
        return self.items.__iter__()

    def __getitem__(self, key):
        return self.items[key]