You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
3.5 KiB

from article.models import Article
from article.serializers import ArticleListSerializer, ArticleDetailSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import Http404
from rest_framework import mixins
from rest_framework import generics
from rest_framework import status
from article.permissions import IsAdminUserOrReadOnly
2 years ago
@api_view(['GET', 'POST'])
def article_list(request):
# 获取所有文章列表
if request.method == 'GET':
articles = Article.objects.all()
serializer = ArticleListSerializer(articles, many=True)
return Response(serializer.data)
# 创建新的文章
elif request.method == 'POST':
serializer = ArticleListSerializer(data=request.data)
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)
# 和article_list()功能相同
class ArticleList(generics.ListCreateAPIView):
# 添加用户权限
permission_classes = [IsAdminUserOrReadOnly]
queryset = Article.objects.all()
serializer_class = ArticleListSerializer
def perform_create(self, serializer):
# 在序列化数据真正保存之前调用
serializer.save(author=self.request.user)
# 第一种版本
# class ArticleDetail(APIView):
# """文章详情视图"""
# def get_object(self, pk):
# """获取单个文章对象"""
# try:
# # pk代表主键
# return Article.objects.get(pk=pk)
# except:
# raise Http404
#
# def get(self, request, pk):
# article = self.get_object(pk)
# serializer = ArticleDetailSerializer(article)
# # 返回Json数据
# return Response(serializer.data)
#
# def put(self, request, pk):
# article = self.get_object(pk)
# serializer = ArticleDetailSerializer(article, data=request.data)
# # 验证提交的数据是否合法
# # 不合法就返回400
# if serializer.is_valid():
# # 序列化器将持有的数据反序列化后
# # 保存到数据库
# serializer.save()
# return Response(serializer.data)
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
# def delete(self, request, pk):
# article = self.get_object(pk=pk)
# article.delete()
# # 删除成功后返回204
# return Response(status=status.HTTP_204_NO_CONTENT)
# 第二种版本
# class ArticleDetail(mixins.RetrieveModelMixin,
# mixins.UpdateModelMixin,
# mixins.DestroyModelMixin,
# generics.GenericAPIView):
# """文章详情视图"""
# queryset = Article.objects.all()
# # 序列化类
# serializer_class = ArticleDetailSerializer
#
# def get(self, request, *args, **kwargs):
# return self.retrieve(request, *args, **kwargs)
#
# def put(self, request, *args, **kwargs):
# return self.update(request, *args, **kwargs)
#
# def delete(self, request, *args, **kwargs):
# return self.destroy(request, *args, **kwargs)
# ArticleDetail类还可以简化为下面的代码
class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [IsAdminUserOrReadOnly]
queryset = Article.objects.all()
serializer_class = ArticleDetailSerializer