RESTful API : 面向资源编程
1 | pip install djangorestframework |
快速使用
1 | # step 1:注册 App -> setting.py |
CBV
- urls.py
1 | urlpatterns = [ |
- view.py
1 | from rest_framework.views import APIView |
- new file serializers.py
1 | from rest_framework import serializers |
总结
- 2 个 url
- 5 个 方法
最多进行跨表查询,综合数据展示出来
参考
DRF doc
1 | from rest_framework.documentation import include_docs_urls |
Django View
使用Django
序列化数据1
2
3
4
5
6from django.views.generic.base import View, ListView, DateDetailView, DeleteView, DatailView, TemplateView
# django 序列化
from django.forms.models import model_to_dict
from dhango.core.serializers import serialize
json_data = serialize('json', <query>)
from django.http import JsonResponse
DRF view
Serializer
数据序列化,如果需要序列化外键的数据就再创建一个Serializer
.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
def create(self, validated_data):
"""
Create and return a new `Snippet` instance, given the validated data.
"""
return Snippet.objects.create(**validated_data)
def update(self, instance, validated_data):
"""
Update and return an existing `Snippet` instance, given the validated data.
"""
instance.title = validated_data.get('title', instance.title)
instance.code = validated_data.get('code', instance.code)
instance.linenos = validated_data.get('linenos', instance.linenos)
instance.language = validated_data.get('language', instance.language)
instance.style = validated_data.get('style', instance.style)
instance.save()
return instance
ModelSerializer
这个可以把所有的字段给省略掉,create
,update
也可以省掉
APIView
数据列表,继承自View
Using mixins | generics
使用mixins
,generics
更高级的封装来更容易的写接口,继承generics
这个文件里面的方法,可以只使用其中某一个功能,但是generics
这个不论什么组合都不能少
mixins
: 数据的操作generics
:http
的操作drf
就是这些的组合
自定义页码
1 | from rest_framework.pagination import PageNumberPagination |
viewsets
各种组合 mixins
, GenericViewSet
这个是推荐,常用的,仅限于 view class,它是通过路由绑定。更高级的封装
- viewsets.GenericViewSet
1 | class Example(mixins.ListModelMinxin, viewsets.GenericViewSet) |
分析 view
generics
里有各种组合view
,
1 | GenericViewSet(viewset) # drf |
mixin1
2
3
4
5CreateModelMixin
ListModelMixin
UpdateModelMixin
RetrieveModelMixin
DestoryModelMixin
req | rep
DRF 中的requests
,response
Filter
1 | pip install django-filter |
Django Filter
1 | import django_filters |
DRF Search Filter | Order Filter
1 | from rest_framework import filters |
HTTP
1 | # 状态 |