rest_framework,示例题
在day95文件夹中:还有部分文件没有写入
1,urls.py(中写入):
from django.conf.urls import url,include
from django.contrib import admin
from app01 import app01_urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'api/',include(app01_urls))
]
2,app01_urls.py(中写入):
from django.conf.urls import url
from app01 import views
urlpatterns = [
url(r'^article/$',views.Article.as_view()),
url(r'article/(?P<pk>\d+)',views.ArticleDetail.as_view(),name='article-detail'),
url(r'school/(?P<id>\d+)',views.SchoolDetail.as_view(),name='school-detail'),
url(r'comment/',views.Comment.as_view()),
# url(r'comment2/$',views.CommentViewSet.as_view({
# 'get':'list',
# 'post':'create'
# })),
# url(r'comment2/(?P<pk>\d+)',views.CommentViewSet.as_view({
# 'get':'retrieve',
# 'put':'update',
# 'delete':'destroy'
# })),
]
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'comment2', views.CommentViewSet)
urlpatterns += router.urls
3,views.py(中写入):
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from app01 import models
from rest_framework import serializers
from django import views
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from app01 import serializers as app01_serializers
from rest_framework.generics import GenericAPIView,RetrieveUpdateDestroyAPIView,ListCreateAPIView
from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin
# Create your views here.
class Comment(APIView):
def get(self,request):
print(request.data)
res = {'code':0}
# print('111')
all_comment = models.Comment.objects.all()
ser_obj = app01_serializers.CommentSerializer(all_comment,many=True)
# print(ser_obj)
res['data'] = ser_obj.data
# print('2222')
return Response(res)
def post(self,request):
res = {'code':0}
comment_data = self.request.data
ser_obj = app01_serializers.CommentSerializer(data=comment_data)
if ser_obj.is_valid():
ser_obj.save()
else:
res['code'] = 1
res['error'] = ser_obj.errors
return Response(res)
# return HttpResponse('创建新评论')
def put(self,request):
print(self.request)
print(self.request.data)
return HttpResponse('修改评论')
def delete(self,request):
print(self.request)
print(self.request.data)
return HttpResponse('删除评论')
class Article(APIView):
def get(self,request):
res = {'code':0}
all_article = models.Article.objects.all()
ser_obj = app01_serializers.ArticleHyperLinkedSerializer(all_article,many=True,context={'request':request})
res['data'] = ser_obj.data
return Response(res)
def post(self,request):
res = {'code':0}
ser_obj = app01_serializers.ArticleModelSerializer(data=self.request.data)
if ser_obj.is_valid():
ser_obj.save()
else:
res['code'] = 1
res['error'] = ser_obj.errors
return Response(res)
class ArticleDetail(APIView):
def get(self,request,pk):
res = {'code':0}
print('1111')
article_obj = models.Article.objects.filter(pk = pk).first()
ser_obj = app01_serializers.ArticleHyperLinkedSerializer(article_obj,context={'request':request})
res['data'] = ser_obj.data
return Response(res)
class SchoolDetail(APIView):
def get(self,request,id):
res = {'code':0}
school_obj = models.School.objects.filter(pk=id).first()
ser_obj = app01_serializers.SchoolSerializer(school_obj,context={'request':request})
res['data'] = ser_obj.data
return Response(res)
# class CommentView(APIView):
# def get(self,request):
# query_set = models.Comment.objects.all()
# ser_obj = app01_serializers.CommentSerializer(query_set,many=True)
# return Response(ser_obj.data)
# class CommentView(GenericAPIView,ListModelMixin,CreateModelMixin):
# queryset = models.Comment.objects.all()
# serializer_class = app01_serializers.CommentSerializer
#
# def get(self,request,*args,**kwargs):
# return self.list(request,*args,**kwargs)
#
# def post(self,request,*args,**kwargs):
# print('要添加评论了')
# return self.create(request,*args,**kwargs)
# class CommentDetailView(GenericAPIView,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin):
# queryset = models.Comment.objects.all()
# serializer_class = app01_serializers.CommentSerializer
#
# def get(self,request,pk):
# return self.retrieve(request,pk)
#
# def delete(self,request,pk):
# return self.destroy(request,pk)
#
# def perform_destroy(self, instance):
# print('删除了。。。')
# instance.delete()
#
# def put(self,request,pk):
# return self.update(request,pk)
# class CommentDetailView(RetrieveUpdateDestroyAPIView):
# queryset = models.Comment.objects.all()
# serializer_class = app01_serializers.CommentSerializer
#
#
# class CommentView(ListCreateAPIView):
# queryset = models.Comment.objects.all()
# serializer_class = app01_serializers.CommentSerializer
class CommentViewSet(ModelViewSet):
queryset = models.Comment.objects.all()
serializer_class = app01_serializers.CommentSerializer
4,serializers.py(中写入):
from app01.models import Comment,Article,School
from rest_framework import serializers
from rest_framework.validators import ValidationError
class CommentSerializer(serializers.ModelSerializer):
def validate_content(self,value):
if '坏' in value:
raise ValidationError('非法字符!')
else:
return value
class Meta:
model = Comment
fields = '__all__'
extra_kwargs = {
'content':{
'error_messages':{
'required':'内容不能为空',
}
},
'article':{
'error_messages':{
'required':'文章不能为空'
}
}
}
class ArticleModelSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
class ArticleHyperLinkedSerializer(serializers.HyperlinkedModelSerializer):
school = serializers.HyperlinkedIdentityField(view_name='school-detail',lookup_url_kwarg='id')
# 路径拼接,
class Meta:
model = Article
fields = ['id','title','type','school']
class SchoolSerializer(serializers.ModelSerializer):
class Meta:
model = School
fields = '__all__'
5,