Пример #1
0
def load_from_path(path):
    """
    Load class or function from string path.
    """
    module, attr = path.rsplit('.', 1)
    mod = importlib.import_module(module)
    return getattr(mod, attr)
Пример #2
0
def load_from_path(path):
    """
    Load class or function from string path.
    """
    module, attr = path.rsplit('.', 1)
    mod = importlib.import_module(module)
    return getattr(mod, attr)
Пример #3
0
def auth_permitted(request):
    """
    Check that the user in request can have access to the view or not.

    By default, all users can edit or revert settings values.
    """
    default = lambda request: True
    func = settings._framework.auth_permitted_func or default

    if isinstance(func, basestring):
        module, attr = func.split('.')

        mod = importlib.import_module(module)
        func = getattr(mod, attr)

    return func(request)
Пример #4
0
def auth_permitted(request):
    """
    Check that the user in request can have access to the view or not.

    By default, all users can edit or revert settings values.
    """
    default = lambda request: True
    func = settings._framework.auth_permitted_func or default

    if isinstance(func, basestring):
        module, attr = func.split('.')

        mod = importlib.import_module(module)
        func = getattr(mod, attr)

    return func(request)
Пример #5
0
    def find_settings_files(self):
        """
        Find configuration definition files from each available installed app
        and from project itself.
        """
        apps = get_apps()
        files = {}
        pathes = self.settings_files

        for app in apps:
            app_name = app.__name__.split('.')[-2]
            path = pathes.get(app_name, DEFAULT_SETTINGS_FILENAME)

            if not os.path.isabs(path):
                dirname = os.path.dirname(app.__file__)
                path = os.path.join(dirname, path)

            if not os.path.isfile(path):
                continue

            files.update({app_name: path})

        for app_name, path in pathes.iteritems():
            if name in files or not os.path.isfile(path):
                continue

            files.update({app_name: path})

        path = self.settings_file or DEFAULT_SETTINGS_FILENAME

        # If path isn't absolute - made it
        if not os.path.isabs(path):
            module = importlib.import_module(django_settings.SETTINGS_MODULE)
            dirname = os.path.dirname(os.path.normpath(module.__file__))
            path = os.path.join(dirname, path)

        files.update({'__project__': path})

        return files
Пример #6
0
    def configure(self, backend=None, framework=None, **kwargs):
        """
        Setup which backend will be used for reading and saving settings data
        and which framework will be used for searching for available settings.
        """
        assert not self._configured, '``LazySettings`` instance already ' \
                                     'configured. Backend: %r, framework: ' \
                                     '%r' % (self._backend, self._framework)

        if framework:
            # Import framework module by the Python path
            try:
                framework_module = importlib.import_module(framework)
            except ImportError:
                message = 'Cannot import framework module from %r path' % \
                          framework
                logger.error(message)

                raise ImproperlyConfigured(message)

            # Load framework class from module if possible
            try:
                framework_klass = getattr(framework_module, 'Framework')
            except AttributeError, e:
                message = 'Cannot import framework class from %r module' % \
                          framework
                logger.error(message)

                raise ImproperlyConfigured(message)

            # Framework class should be an instance of ``SetmanFramework``
            if not issubclass(framework_klass, SetmanFramework):
                message = '%r is not a subclass of %r' % \
                          (framework_klass, SetmanFramework)
                logger.error(message)

                raise ImproperlyConfigured(message)
Пример #7
0
    def configure(self, backend=None, framework=None, **kwargs):
        """
        Setup which backend will be used for reading and saving settings data
        and which framework will be used for searching for available settings.
        """
        assert not self._configured, '``LazySettings`` instance already ' \
                                     'configured. Backend: %r, framework: ' \
                                     '%r' % (self._backend, self._framework)

        if framework:
            # Import framework module by the Python path
            try:
                framework_module = importlib.import_module(framework)
            except ImportError:
                message = 'Cannot import framework module from %r path' % \
                          framework
                logger.error(message)

                raise ImproperlyConfigured(message)

            # Load framework class from module if possible
            try:
                framework_klass = getattr(framework_module, 'Framework')
            except AttributeError, e:
                message = 'Cannot import framework class from %r module' % \
                          framework
                logger.error(message)

                raise ImproperlyConfigured(message)

            # Framework class should be an instance of ``SetmanFramework``
            if not issubclass(framework_klass, SetmanFramework):
                message = '%r is not a subclass of %r' % \
                          (framework_klass, SetmanFramework)
                logger.error(message)

                raise ImproperlyConfigured(message)
Пример #8
0
                raise ImproperlyConfigured(message)

            # Framework class should be an instance of ``SetmanFramework``
            if not issubclass(framework_klass, SetmanFramework):
                message = '%r is not a subclass of %r' % \
                          (framework_klass, SetmanFramework)
                logger.error(message)

                raise ImproperlyConfigured(message)
        else:
            # If no framework would be set - we will use default class
            framework_klass = SetmanFramework

        if backend:
            try:
                backend_module = importlib.import_module(backend)
            except ImportError, e:
                message = 'Cannot import backend module from %r path' % backend
                logger.error(message)

                raise ImproperlyConfigured(message)

            try:
                backend_klass = getattr(backend_module, 'Backend')
            except AttributeError, e:
                message = 'Cannot import backend class from %r module' % \
                          backend
                logger.error(message)

                raise ImproperlyConfigured(message)
Пример #9
0
    def _parse_choices(self, value):
        """
        Convert string value to valid choices tuple.

        **Supported formats:**

        * a, b, c
        * (a, A), (b, B), (c, C)
        * a { b, c }, d { e, f }
        * A { (b, B), (c, C) }, D { (e, E), (f, F) }
        * path.to.CHOICES
        * path.to.Model.CHOICES

        """
        # Start parsing with internal choices
        if not ',' in value and '.' in value:
            # Choices tuple should be last part of value
            path, attr = value.rsplit('.', 1)

            # Load choices from module
            try:
                module = importlib.import_module(path)
            except ImportError:
                # Or from module class
                try:
                    module = load_from_path(path)
                except (AttributeError, ImportError):
                    logger.exception('Cannot load choices from %r path', value)
                    return ()

            # Try to get choices attr in module
            try:
                choices = getattr(module, attr)
            except AttributeError:
                logger.exception('Cannot load choices from %r path', value)
                return ()
        elif not '{' in value and not '}' in value:
            # Parse choice with labels
            label_re = re.compile(r'\(([^,]+),\s+([^\)]+)\)', re.M)
            found = label_re.findall(value)

            if found:
                choices = found
            # If nothing found by regex, just split value by comma and
            # duplicate resulted items
            else:
                choices = map(lambda item: (item.strip(), item.strip()),
                              value.split(','))
        else:
            # Parse groups
            groups_re = re.compile(r'([^{]+){([^}]+)},?', re.M)
            found = groups_re.findall(value)

            if found:
                choices = []

                for group, data in found:
                    group = group.strip()
                    choices.append((group, self._parse_choices(data.strip())))
            else:
                logger.error('Cannot parse choices from %r', value)
                return ()

        return tuple(choices)
Пример #10
0
                raise ImproperlyConfigured(message)

            # Framework class should be an instance of ``SetmanFramework``
            if not issubclass(framework_klass, SetmanFramework):
                message = '%r is not a subclass of %r' % \
                          (framework_klass, SetmanFramework)
                logger.error(message)

                raise ImproperlyConfigured(message)
        else:
            # If no framework would be set - we will use default class
            framework_klass = SetmanFramework

        if backend:
            try:
                backend_module = importlib.import_module(backend)
            except ImportError, e:
                message = 'Cannot import backend module from %r path' % backend
                logger.error(message)

                raise ImproperlyConfigured(message)

            try:
                backend_klass = getattr(backend_module, 'Backend')
            except AttributeError, e:
                message = 'Cannot import backend class from %r module' % \
                          backend
                logger.error(message)

                raise ImproperlyConfigured(message)
Пример #11
0
    def _parse_choices(self, value):
        """
        Convert string value to valid choices tuple.

        **Supported formats:**

        * a, b, c
        * (a, A), (b, B), (c, C)
        * a { b, c }, d { e, f }
        * A { (b, B), (c, C) }, D { (e, E), (f, F) }
        * path.to.CHOICES
        * path.to.Model.CHOICES

        """
        # Start parsing with internal choices
        if not ',' in value and '.' in value:
            # Choices tuple should be last part of value
            path, attr = value.rsplit('.', 1)

            # Load choices from module
            try:
                module = importlib.import_module(path)
            except ImportError:
                # Or from module class
                try:
                    module = load_from_path(path)
                except (AttributeError, ImportError):
                    logger.exception('Cannot load choices from %r path',
                                     value)
                    return ()

            # Try to get choices attr in module
            try:
                choices = getattr(module, attr)
            except AttributeError:
                logger.exception('Cannot load choices from %r path', value)
                return ()
        elif not '{' in value and not '}' in value:
            # Parse choice with labels
            label_re = re.compile(r'\(([^,]+),\s+([^\)]+)\)', re.M)
            found = label_re.findall(value)

            if found:
                choices = found
            # If nothing found by regex, just split value by comma and
            # duplicate resulted items
            else:
                choices = map(lambda item: (item.strip(), item.strip()),
                              value.split(','))
        else:
            # Parse groups
            groups_re = re.compile(r'([^{]+){([^}]+)},?', re.M)
            found = groups_re.findall(value)

            if found:
                choices = []

                for group, data in found:
                    group = group.strip()
                    choices.append((group, self._parse_choices(data.strip())))
            else:
                logger.error('Cannot parse choices from %r', value)
                return ()

        return tuple(choices)