djangorest框架是今天看的一个文档。
比较简单的是入门篇,
https://github.com/moocstudent/django-proj
这个呢就是根据入门篇来的代码,
其中比django原教程多的就是关于深入的rest框架的关键点使用。
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
# Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets.
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
比如下面这里的ModelViewSet就是一个通用的restful接口组件,
from django.contrib.auth.models import User, Group
from rest_framework import serializers
# Notice that we're using hyperlinked relations in this case with HyperlinkedModelSerializer.
# You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
class UserSerializer(serializers.HyperlinkedModelSerializer):
# meta data set
class Meta:
model = User
# custom fields
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
再比如serializer序列化,这个序列化类在view层进行了指定。
最后接口的路由是通过urls配置的:
from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views
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 = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
整理也就是说前端请求过来之后通过urls找到相应接口路由,
再找到视图views,然后处理相关逻辑,而serializer类似一个处理单元。
在serializer中,原本配置比较多
from rest_framework import serializers
import snippets.models
class SnippetSerializer(serializers.ModelSerializer):
# 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')
class Meta:
model = Snippet
fields = ['id','title','code','linenos','language','style']
# 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
如果上面第一行是class SnippetSerializer(serializers.Serializer)的话对应注释代码也是
配合serializers.Serializer的,而ModelSerializer则提供了通用的方法。