django rest framework 实现api接口

安装

pip install djangorestframework

settings配置

INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken',]

api.py

app目录下新建api.py

from website.models import Video
from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes
from rest_framework.authentication import TokenAuthentication

class VideoSerializer(serializers.ModelSerializer):
    title = serializers.CharField(min_length=1)
    class Meta:
        model = Video
        fields = '__all__'

@api_view(['GET', 'POST'])
def video(request):
    print(request.user)
    print('$'*45)
    if request.method == 'GET':
        video_list = Video.objects.order_by('-id')
        serializer = VideoSerializer(video_list, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = VideoSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        body = { 'body': serializer.errors,            'msg': '40001'        }
        return Response(body, status=status.HTTP_400_BAD_REQUEST)
        

urls.py

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容