安装
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)