fields.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:flask-zhenai-mongo-echarts 作者: Fretice 项目源码 文件源码
def to_python(self, value):
        """Convert a MongoDB-compatible type to a Python type."""
        if isinstance(value, six.string_types):
            return value

        if hasattr(value, 'to_python'):
            return value.to_python()

        is_list = False
        if not hasattr(value, 'items'):
            try:
                is_list = True
                value = {k: v for k, v in enumerate(value)}
            except TypeError:  # Not iterable return the value
                return value

        if self.field:
            self.field._auto_dereference = self._auto_dereference
            value_dict = {key: self.field.to_python(item)
                          for key, item in list(value.items())}
        else:
            Document = _import_class('Document')
            value_dict = {}
            for k, v in list(value.items()):
                if isinstance(v, Document):
                    # We need the id from the saved object to create the DBRef
                    if v.pk is None:
                        self.error('You can only reference documents once they'
                                   ' have been saved to the database')
                    collection = v._get_collection_name()
                    value_dict[k] = DBRef(collection, v.pk)
                elif hasattr(v, 'to_python'):
                    value_dict[k] = v.to_python()
                else:
                    value_dict[k] = self.to_python(v)

        if is_list:  # Convert back to a list
            return [v for _, v in sorted(list(value_dict.items()),
                                         key=operator.itemgetter(0))]
        return value_dict
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号