views.py
# get所需的
from snippets.serializers import SnippetSerializer
from rest_framework.views import APIView
from rest_framework.response import Response # 是drf的response
# post所需的
from snippets.models import Snippet
from django.http import Http404
from rest_framework import status
class SnippetList(APIView):
"""
这是SnippetList接口的一些描述信息
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
"""获取"""
snippets = Snippet.objects.all()
snippets_serializer = SnippetSerializer(snippets, many=True)
return Response(snippets_serializer.data)
def post(self, request, format=None):
serializer = SnippetSerializer(data=request.data) # drf的request,可以直接取出用户过来的body数据 / post数据
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
#!/usr/bin/env python
# coding=utf-8
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True) # read_only先不管
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
snippets/urls.py
from django.urls import path, include
from django.conf.urls import url
from snippets import views
app_name = 'snippets'
urlpatterns = [
# path('', views.index, name="index"),
path('snippets', views.SnippetList.as_view(), name="snippets"),
]
urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
urlpatterns = [
path('app01/', include("app01.urls")),
path('app02/', include("app02.urls")),
path('app03/', include("app03.urls")),
path('app04/', include("app04.urls")),
path('app05/', include("app05.urls")),
path('app06/', include("app06.urls")),
path('app07/', include("app07.urls")),
path('app08/', include("app08.urls")),
path('snippets/', include("snippets.urls")),
path('admin/', admin.site.urls),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
添加数据
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
"code": "print \"hello, world\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
http://www.django-rest-framework.org/tutorial/1-serialization/#using-modelserializers
# 使用ModelSerializer,类似modelform, http://www.django-rest-framework.org/tutorial/1-serialization/#using-modelserializers
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
# fields ="__all__"
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
嵌套
优化listview: http://www.django-rest-framework.org/tutorial/3-class-based-views/
ListAPIView get
RetrieveAPIView get
DestroyAPIView delete
UpdateAPIView update
ListCreateAPIView get/post
RetrieveUpdateAPIView get/put/patch
RetrieveDestroyAPIView get/delete
RetrieveUpdateDestroyAPIView get/put/patch/delete
分页
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 1
}
使用api