Exemple #1
0
    def get_fields(cls):
        """
        主要包括'Meta.fields'且不在'Meta.exclude'中的字段
        :return:
        """
        meta_class = getattr(cls, "_meta")
        model = meta_class.model
        fields = meta_class.fields
        exclude = meta_class.exclude

        if fields is None and exclude is None:
            raise ImproperlyConfigured(
                "Creating a FilterSet without either the 'fields' attribute "
                "or the 'exclude' attribute is prohibited; filter %s "
                "needs updating." % cls.__name__
            )

        # 无字段设置排除意味着所有其他字段.
        if exclude is not None and fields is None:
            fields = ALL_FIELDS

        if fields == ALL_FIELDS:
            fields = model._meta.sorted_field_names

        # 移除`Meta.exclude`中的字段
        exclude = exclude or []
        if not isinstance(fields, dict):
            fields = [(f, ['exact']) for f in fields if f not in exclude]
        else:
            fields = [(f, lookups) for f, lookups in fields.items() if f not in exclude]

        return OrderedDict(fields)
Exemple #2
0
    def construct_ordering(self, ordering, queryset):
        query_model_fields = self.get_query_model_fields(queryset)
        norm_order_by = []
        query_model_name = queryset.model_class.__name__
        for item in ordering:
            if isinstance(item, models.Field):
                prefix = '-' if item._ordering.lower() == 'desc' else ''
                if query_model_name == item.model_class.__name__:
                    item = "{prefix}{field_name}".format(prefix=prefix,
                                                         field_name=item.name)
                else:
                    item = "{prefix}{model_name}.{field_name}".format(
                        prefix=prefix,
                        model_name=item.model_class._meta.name,
                        field_name=item.name)

            prefix = "-" if "-" in item else "+"
            field_name = item.lstrip(prefix)
            field = query_model_fields.get(field_name, None)
            if field is None:
                error_msg = "排序字段{field_name}无法在queryset.model_class或queryset.join的model找到".format(
                    field_name=field_name)
                raise ImproperlyConfigured(error_msg)

            norm_order_by.append(
                field.desc() if item.startswith('-') else field.asc())

        return norm_order_by
Exemple #3
0
def get_hashers():
    hashers = []
    for hasher_path in settings.PASSWORD_HASHERS:
        hasher = import_object(hasher_path)()
        if not getattr(hasher, 'algorithm'):
            raise ImproperlyConfigured(
                "hasher doesn't specify an algorithm name: %s" % hasher_path)
        hashers.append(hasher)
    return hashers
    def databases(self):
        if self._databases is None:
            self._databases = settings.DATABASES

        if self._databases and DEFAULT_DB_ALIAS not in self._databases:
            raise ImproperlyConfigured("You must define a '%s' database" %
                                       DEFAULT_DB_ALIAS)

        return self._databases
def _create_cache(cache_config, **kwargs):
    try:
        params = cache_config
        params.update(kwargs)
        backend = params.get('BACKEND')
        location = params.get('LOCATION', '')
        backend_module = import_module(backend)
    except ImportError as e:
        raise ImproperlyConfigured("Could not find backend '%s': %s" % (backend, e))

    return backend_module.CacheWrapper(location, params)
def get_parsers():
    parsers = []
    for parser_path in settings.PARSER_CLASSES:
        parser = import_object(parser_path)()
        if not getattr(parser, 'media_type'):
            raise ImproperlyConfigured(
                "parser没有定义media_type值: {parser_path}".format(
                    parser_path=parser_path))
        parsers.append(parser)

    return parsers
 def load_backend(backend_name):
     """
     加载数据库连接处理块,如果不存在,则抛出异常
     :param backend_name:
     :return:
     """
     try:
         return import_module(backend_name)
     except ImportError as e_user:
         raise ImproperlyConfigured(
             "{backend_name} isn't an available database backend."
             "\nError was: {msg}".format(backend_name=backend_name,
                                         msg=e_user))
    def filter(self, qs, value):
        if self.distinct:
            qs = qs.distinct()

        if not value or (value.start is None and value.stop is None):
            return qs

        if self.source is None:
            field_name = self.field_name
        else:
            field_name = self.source

        if isinstance(field_name, models.Field):
            field = field_name
        elif isinstance(field_name, str) and "." in field_name:
            join_fields = self.get_join_fields(qs)
            field = join_fields[field_name.lower()]
        else:
            field = getattr(qs.model_class, field_name)

        if field is None:
            error_msg = "字段{field_name}无法在queryset.model_class或queryset.join的model找到".format(
                field_name=field_name)
            raise ImproperlyConfigured(error_msg)

        expressions = None
        if value.start is not None and value.stop is not None:
            expressions = [
                models.Expression(
                    field, models.OP.BETWEEN,
                    models.Clause(value.start, models.R('AND'), value.stop))
            ]
        else:
            if value.start is not None:
                expressions = [
                    models.Expression(field, models.OP.GTE, value.start)
                ]
            if value.stop is not None:
                expressions = [
                    models.Expression(field, models.OP.LTE, value.stop)
                ]

        if expressions is None:
            return qs

        qs_expressions = reduce(operator.and_, expressions)
        qs = self.get_method(qs)(qs_expressions)
        return qs
Exemple #9
0
    def __getitem__(self, alias):
        try:
            return self._caches.caches[alias]
        except AttributeError:
            self._caches.caches = {}
        except KeyError:
            pass

        cache_configs = settings.CACHES
        if alias not in cache_configs:
            raise ImproperlyConfigured(
                "Could not find config for '%s' in settings.CACHES" % alias)

        cache_backend = _create_cache(cache_configs[alias])
        self._caches.caches[alias] = cache_backend
        return cache_backend
Exemple #10
0
    def __new__(mcs, name, bases, attrs):
        new_class = super(ModelFormMetaclass,
                          mcs).__new__(mcs, name, bases, attrs)

        if bases == (BaseModelForm, ):
            return new_class

        form_opts = new_class._meta = ModelFormOptions(
            getattr(new_class, 'Meta', None))

        if form_opts.model:
            # If a model is defined, extract form fields from it.
            if form_opts.fields is None and form_opts.exclude is None:
                raise ImproperlyConfigured(
                    "Creating a ModelForm without either the 'fields' attribute "
                    "or the 'exclude' attribute is prohibited; form %s "
                    "needs updating." % name)

            if isinstance(form_opts.fields,
                          str) and form_opts.fields.lower() == ALL_FIELDS:
                form_opts.fields = None

            model_fields = fields_for_model(
                model=form_opts.model,
                fields=form_opts.fields,
                exclude=form_opts.exclude,
                extra_kwargs=form_opts.extra_kwargs)

            # make sure opts.fields doesn't specify an invalid field
            none_model_fields = [k for k, v in model_fields.items() if not v]
            missing_fields = (set(none_model_fields) -
                              set(new_class.declared_fields.keys()))
            if missing_fields:
                message = 'Unknown field(s) (%s) specified for %s'
                message = message % ', '.join(
                    missing_fields), form_opts.model.__name__
                raise FieldError(message)
            model_form_fields = model_fields
            model_form_fields.update(new_class.declared_fields)
        else:
            model_form_fields = new_class.declared_fields

        new_class.base_fields = model_form_fields

        return new_class
Exemple #11
0
    def construct_search(self, query_model_fields, field_name):
        """
        根据搜索字段的配置,构建搜索匹配模式进行返回
        :param query_model_fields:
        :param field_name:
        :return:
        """
        lookup = self.lookup_prefixes.get(field_name[0])

        if lookup:
            field_name = field_name[1:]
        else:
            lookup = (models.OP.ILIKE, '%%%s%%')

        field = query_model_fields.get(field_name.lower(), None)
        if field is None:
            error_msg = "搜索字段{field_name}无法在queryset.model_class或queryset.join的model找到".format(
                field_name=field_name)
            raise ImproperlyConfigured(error_msg)

        return field, lookup[0], lookup[1]
    def __new__(mcs, name, bases, attrs):
        new_class = super(ModelSerializerMetaclass,
                          mcs).__new__(mcs, name, bases, attrs)
        opts = new_class._meta = ModelSerializerOptions(
            getattr(new_class, 'Meta', None))

        if opts.model:
            if opts.fields is None and opts.exclude is None:
                raise ImproperlyConfigured(
                    "Creating a ModelSerializer without either the 'fields' attribute "
                    "or the 'exclude' attribute is prohibited; ModelSerializer %s "
                    "needs updating." % name)

            if isinstance(opts.fields,
                          str) and opts.fields.lower() == ALL_FIELDS:
                opts.fields = None

            fields = fields_for_model(model=opts.model,
                                      fields=opts.fields,
                                      exclude=opts.exclude)

            none_model_fields = [k for k, v in fields.items() if not v]
            missing_fields = (set(none_model_fields) -
                              set(new_class.declared_fields.keys()))
            if missing_fields:
                message = 'Unknown field(s) (%s) specified for %s'
                message = message % ', '.join(
                    missing_fields), opts.model.__name__
                raise FieldError(message)
            fields.update(new_class.declared_fields)
        else:
            fields = new_class.declared_fields

        new_class.base_fields = fields

        return new_class