django 中api使用之django-rest-framework
2018-03-20 22:15
615 查看
安装
pip install djangorestframework
serializers
序列化实例(http://www.django-rest-framework.org/api-guide/serializers/)字段 fields 可以用特定的值,也可以使用 fields = ‘all‘来实例化所有
from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = '__all__'
不同的实例化区别
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field. The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field.
tips:当使用HyperlinkedModelSerializer的时候不能使用 fields = ‘all‘,不然会报错,错误信息如下:
ImproperlyConfigured at /ofc/rest_api/custom Could not resolve URL for hyperlinked relationship using view name "mdcustoms-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
view
class CustomDetail(viewsets.ModelViewSet): queryset = Custom.objects.all().order_by('-date_joined') serializer_class = CustomSerializer
当然在rest_framework中封装了很多库,比如附待参数generics.ListAPIView,从而使它的写法更简单
class CustomDetail(generics.ListAPIView): queryset = MdCustoms.objects.all() serializer_class = MDCustomSerializer pagination_class = LargeResultsSetPagination filter_fields = '__all__'
urls
在django2.0版本中path("rest_api/custom", rest_model.CustomDetail.as_view(), name="rest_mdcustom"),
或者在低版,可以使用类似这种写法
router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
Settings
将rest_framework组建添加到INSTALLED_APPS中:INSTALLED_APPS = ( ... 'rest_framework', )
支持筛选
# 使支持django-filter 的条件筛选 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
分页
参考:http://www.django-rest-framework.org/api-guide/pagination/分页,可配置的选项比较丰富了,这里使用一个可定义的page方法
在setting里配置
REST_FRAMEWORK = { # 分页查询 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', 'PAGE_SIZE': 5,
编写对应的类
class LargeResultsSetPagination(PageNumberPagination):
page_size = 1000
page_size_query_param = 'page_size'
max_page_size = 10000
对应的应用
class CustomDetail(generics.ListAPIView): queryset = MdCustoms.objects.all() serializer_class = MDCustomSerializer pagination_class = LargeResultsSetPagination filter_fields = '__all__'
介绍就到这里了, 用django-rest-framework的相关代码上传到github上,用django-rest-framework写的api查询拉钩上工作信息:https://github.com/huangxifa/job
相关文章推荐
- Django REST framework笔记一之简易JsonAPI搭建(可使用)
- 使用Django rest framework api时,客户端返回结果为html标签
- 学习使用"Django REST framework"打造RESTful API接口——第一节 quickstart
- Django rest framework API Guide的 Generic views 翻译
- django-rest-framework序列化的使用(一)
- django-rest-framework过滤器的使用(三)
- django使用rest_framework
- django rest framework使用django-filter
- django-rest-framework视图层的使用(二)
- Django REST Framework Tutorial 5:关系与超链接API(中文版教程)by hillfree
- python调试django-rest-framework API的小工具--httpie
- Django rest framework API Guide的 Views 翻译
- django-rest-framework第一次使用使用常见问题
- Django REST Framework(一) 初步使用
- django-rest-framework 使用例子
- django使用rest_framework API认证
- Django rest framework API Guide的 Requests 翻译
- Django之REST_framework 框架基本组件使用
- tastypie Django REST framework API [Hello JSON]
- Django-Rest-Framework 教程: 3. 使用 class based views