django rest框架的marshmallow模式
django-rest-marshmallow的Python项目详细描述
django-rest-marshmallow
Marshmallow schemas用于django rest框架。
概述
django-rest-marshmallow
通过使用python marshmallow库,为内置序列化程序提供了另一种序列化程序实现,但公开了与rest框架的Serializer
类相同的api。
要求
- Python(2.7,3.5+)
- django rest框架(3.8+)
- 棉花糖(2.15+和3.0.0b18+)
安装
使用pip
安装…
$ pip install django-rest-marshmallow
用法
像使用棉花糖一样定义模式,但是从rest_marshmallow
导入Schema
类。
fromrest_marshmallowimportSchema,fieldsclassCustomerSchema(Schema):name=fields.String()email=fields.Email()created_at=fields.DateTime()
schema类与django rest框架序列化程序具有相同的接口,因此可以在泛型视图中使用它…
classCustomerListView(generics.ListAPIView):queryset=Customer.objects.all()serializer_class=CustomerSchema
或者直接使用序列化程序API,以进行序列化…
serializer=CustomerSchema(queryset,many=True)returnResponse(serializer.data)
或者为了验证…
serializer=CustomerSchema(data=request.data)serializer.is_valid(raise_exception=True)serializer.validated_data
创建和更新实例
如果要支持serializer.save()
,则需要显式定义.create()
和/或.update()
方法。
classCustomerSchema(Schema):name=fields.String()email=fields.Email()created_at=fields.DateTime()defcreate(self,validated_data):returnCustomer.objects.create(**validated_data)defupdate(self,instance,validated_data):forkey,valueinvalidated_data.items():setattr(instance,key,value)instance.save()returninstance
现在可以从视图代码中使用.save()
…
serializer=CustomerSchema(data=request.data)serializer.is_valid(raise_exception=True)serializer.save()returnResponse(serializer.data,status=status.HTTP_201_CREATED)
或者将架构与创建或更新实例的泛型视图一起使用…
classCustomerListView(generics.ListCreateAPIView):queryset=Customer.objects.all()serializer_class=CustomerSchema
注意,应该始终使用create()
和update()
方法,而不是重写make_object()
棉花糖方法。
嵌套表示
对于嵌套表示,像往常一样使用marshmallow的标准Nested
字段。
fromrest_marshmallowimportfields,SchemaclassArtistSchema(Schema):name=fields.String()classAlbumSchema(Schema):title=fields.String()release_date=fields.Date()artist=fields.Nested(ArtistSchema)
不包括字段
棉花糖参数only
和exclude
也可用作序列化器参数:
serializer=CustomerSchema(queryset,many=True,only=('name','email'))returnResponse(serializer.data)
测试
安装测试要求。
$ pip install -r requirements.txt
使用运行测试运行。
$ ./runtests.py
您还可以使用优秀的tox测试工具对所有受支持的python和django版本运行测试。全局安装tox,然后只需运行:
$ tox
文档
要构建文档,您需要安装mkdocs
。
$ pip install mkdocs
预览文档:
$ mkdocs serve Running at: http://127.0.0.1:8000/
构建文档:
$ mkdocs build