def to_representation(self, value):

        if isinstance(value, (DBRef, Document)):
            #Will not get DBRefs thanks to how MongoEngine handles DynamicFields
            #but, respect depth anyways.
            if self.go_deeper(is_ref=True):
                cls = type(value)
                if type(cls) not in self.serializers:
                    self.serializers[cls] = BindingDict(self)
                    for key, val in self.get_document_subfields(cls).items():
                        self.serializers[cls][key] = val
                fields = self.serializers[cls]

                ret = OrderedDict()
                for field in fields:
                    field_value = value._data[field]
                    ret[field] = fields[field].to_representation(field_value)
                return ret
            else:
                #out of depth
                return smart_str(value.id)
        elif isinstance(value, EmbeddedDocument):
            if self.go_deeper():
                cls = type(value)

                if type(cls) not in self.serializers:
                    self.serializers[cls] = BindingDict(self)
                    for key, val in self.get_document_subfields(cls).items():
                        self.serializers[cls][key] = val
                fields = self.serializers[cls]

                ret = OrderedDict()
                for field in fields:
                    field_value = value._data[field]
                    ret[field] = fields[field].to_representation(field_value)
                return ret
            else:
                #out of depth
                return "%s Object: Out of Depth" % type(value).__name__

        elif isinstance(value, ObjectId):
            return smart_str(value)

        elif isinstance(value, list):
            #list of things.
            #dyn = DynamicField(**self.get_field_kwargs(self.model_field))
            return [self.to_representation(i) for i in value]

        else:
            #some other type of value.
            if isinstance(value, numbers.Number):
                return value

            return value
Ejemplo n.º 2
0
    def optimizers(self):
        if not hasattr(self, '_optimizers'):
            self._optimizers = BindingDict(self)
            for key, value in six.iteritems(self.get_optimizers()):
                self._optimizers[key] = value

        return self._optimizers
Ejemplo n.º 3
0
 def fields(self):
     fields = BindingDict(self)
     if self.conditions:
         for key, value in self.get_fields().items():
             if self._check_condition(key):
                 fields[key] = value
     return fields
Ejemplo n.º 4
0
 def fields(self):
     """
     A dictionary of {field_name: field_instance}.
     """
     # `fields` is evaluated lazily. We do this to ensure that we don't
     # have issues importing modules that use ModelSerializers as
     # fields, even if Django's app-loading stage has not yet run.
     if not hasattr(self, '_fields'):
         self._fields = BindingDict(self)
         for key, value in self.get_fields().items():
             self._fields[key] = value
     return self._fields
Ejemplo n.º 5
0
 def __init__(self, data):
     fields = BindingDict(self)
     for key, value in self.get_fields().items():
         fields[key] = value
     if data:
         set1 = set(data[0].keys())
         set2 = set(fields)
         is_subset = set1.issubset(set2)
         if not is_subset:
             raise serializers.ValidationError(
                 "Serializer data is not accepted.")
     else:
         raise serializers.ValidationError("Empty event parameter.")
     super().__init__(self)
Ejemplo n.º 6
0
    def fields(self):
        fields = BindingDict(self)
        for key, value in self.get_fields().items():
            fields[key] = value

        if not hasattr(self, '_context'):
            return fields
        is_root = self.root == self
        parent_is_list_root = self.parent == self.root and getattr(self.parent, 'many', False)
        if not (is_root or parent_is_list_root):
            return fields

        try:
            request = self.request or self.context['request']
        except KeyError:
            return fields
        params = getattr(
            request, 'query_params', getattr(request, 'GET', None)
        )
        if params is None:
            pass
        try:
            filter_fields = params.get('_fields', None).split(',')
        except AttributeError:
            filter_fields = None

        try:
            omit_fields = params.get('_omit', None).split(',')
        except AttributeError:
            omit_fields = []

        existing = set(fields.keys())
        if filter_fields is None:
            allowed = existing
        else:
            allowed = set(filter(None, filter_fields))

        omitted = set(filter(None, omit_fields))
        for field in existing:
            if field not in allowed:
                fields.pop(field, None)
            if field in omitted:
                fields.pop(field, None)

        return fields
    def __getitem__(self, item):
        if not isinstance(item, type):
            item = item.__class__

        #if we haven't initialized the base_dict, use the serializer's field property.
        if not hasattr(self, 'base_dict'):
            self.base_dict = self.serializer.fields
            self.lookup[self.klass] = ChainMap(self.base_dict)

        #see if we've generated this chainmap yet.
        if item in self.lookup:
            return self.lookup[item]

        #check if we can generate it, then generate it.
        if not issubclass(item, self.klass):
            raise AssertionError(
                "Can only serialize objects that inherit from the base model.")

        last_kls = self.klass

        for kls in inspect.getmro(item)[::-1]:
            if issubclass(self.klass, kls):
                continue
            if kls in self.lookup:
                last_kls = kls
                continue
            #{key: value for key, value in instance.__class__._fields.items() if value not in self.Meta.model._fields.values()}
            delta = {
                key: field
                for key, field in kls._fields.items()
                if field not in last_kls._fields.values()
            }

            #construct the next tier of the chainmap
            delta_fields = BindingDict(self.serializer)
            for key, field in delta.items():
                delta_fields[key] = self.serializer.get_field_mapping(field)(
                    **self.serializer.get_field_kwargs(field))

            self.lookup[kls] = ChainMap(delta_fields, self.lookup[last_kls])
        return self.lookup[kls]
    def to_representation(self, value):
        ret = OrderedDict()

        for key in value:
            item = value[key]

            if isinstance(item, DBRef):
                #DBRef, so this is a model.
                if self.go_deeper(is_ref=True):
                    #have depth, we must go deeper.
                    #serialize-on-the-fly! (patent pending)
                    item = DeReference()([item])[0]
                    cls = item.__class__
                    if type(cls) not in self.serializers:
                        self.serializers[cls] = BindingDict(self)
                        for key, val in self.get_document_subfields(cls).items():
                            self.serializers[cls][key] = val
                    fields = self.serializers[cls]

                    sub_ret = OrderedDict()
                    for field in fields:
                        field_value = item._data[field]
                        sub_ret[field] = fields[field].to_representation(field_value)
                    ret[key] = sub_ret
                else:
                    #no depth, so just pretty-print the dbref.
                    ret[key] = smart_str(item.id)
            elif isinstance(item, dict) and '_cls' in item and item['_cls'] in _document_registry:
                #has _cls, isn't a dbref, but is in the document registry - should be an embedded document.
                if self.go_deeper():
                    cls = get_document(item['_cls'])
                    #instantiate EmbeddedDocument object
                    item = cls._from_son(item)

                    #get serializer fields from cache, or make them if needed.
                    if type(cls) not in self.serializers:
                        self.serializers[cls] = BindingDict(self)
                        for key, val in self.get_document_subfields(cls).items():
                            self.serializers[cls][key] = val
                        fields = self.serializers[cls]

                    #iterate.
                    sub_ret = OrderedDict()
                    for field in fields:
                        field_value = item._data[field]
                        sub_ret[field] = fields[field].to_representation(field_value)
                    ret[key] = sub_ret

                else:
                    #no depth, just print the something representing the EmbeddedDocument.
                    cls = item['_cls']
                    ret[key] = "Embedded Document " + cls + " (out of depth)"
                    #TODO - raise an error here instead.

            elif isinstance(value, ObjectId):
                ret[key] = smart_str(value)

            elif isinstance(item, list):
                #list of things.
                dyn = DynamicField(**self.get_field_kwargs(self.model_field))
                ret[key] = [dyn.to_representation(i) for i in item]
            elif isinstance(item, numbers.Number) or isinstance(item, bool):
                #number/bool, just return the value.
                ret[key] = item
            else:
                #stringify
                ret[key] = smart_str(item)

        return ret