单条数据的增删改查
class Books(APIView):
"""
{
"name":"水浒传",
"price":"88.88",
"author":[1, 2, 3 ]
}
"""
def post(self, request):
book_dic = request.data
book_json = objson.BookJson(data=book_dic)
if book_json.is_valid():
book_json.save()
return Response({
'status': 0,
'msg': 'ok',
'results': book_json.data
})
class Book(APIView):
def get(self, request, id):
book_obj = models.Book.objects.filter(pk=id).first()
book_data = objson.BookJson(book_obj).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
def put(self, request, id):
book_obj = models.Book.objects.filter(pk=id).first()
book_json = objson.BookJson(data=request.data, instance=book_obj)
if book_json.is_valid():
book_json.save()
return Response({
'status': 0,
'msg': 'ok',
'results': book_json.data
})
def delete(self, request, id):
models.Book.objects.filter(pk=id).delete()
return Response({
'status': 2,
'msg': 'delete success',
})
数据的校验
class Books(APIView):
def post(self, request):
book_dic = request.data
book_json = objson.BookJson(data=book_dic)
if book_json.is_valid():
return Response({
'status': 0,
'msg': 'ok',
'results': book_json.data
})
return Response({
'status': 0,
'msg': book_json.errors,
})
class BookJson(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = '__all__'
name = serializers.CharField(
max_length=5,
min_length=1,
error_messages={
"max_length": "太长了",
"min_length": "太短了",
}
)
def validate_name(self, value):
from rest_framework.exceptions import ValidationError
if 'sb' in value:
raise ValidationError("出现了敏感词汇")
return value
def validate(self, attrs):
from rest_framework.exceptions import ValidationError
pwd = attrs.get('pwd')
re_pwd = attrs.get('re_pwd')
if pwd == re_pwd:
return attrs
else:
raise ValidationError('密码校验失败')
注销:在全局认证的情况下
class Logout(APIView):
def(self,request):
models.UserToken.objects.updateorcreate(user=request.user,default={'token':common.get_token()})
return Response({'status':0,
'msg':'logout success',
})