序列化组件:
1 对应着表,写序列化的类
2 from rest_framework import serializers
3 写一个类,继承serializers.Serializer
4 类中写一些属性
-name = serializers.CharField()
5 使用:
-实例化产生一个对象(传参数)
-对象.data ---->拿到字典
6 其他:
-source:可以指定字段,也可以指定方法
-serializers.SerializerMethodField()
必须要写一个方法预制对应
get_字段名(self,obj对象)
-HyperlinkedIdentityField
-传三个参数:第一个路由名字,用来反向解析,第二个参数是要反向解析的参数值,第三个参数:有名分组的名字
-xx=HyperlinkedIdentityField(view_name='路由名字',look_up_field='publish_id',lookup_url_kwarg='pky')
-xx=http://127.0.0.1:8001/publish/1
-数据校验
-生成序列化类对象的时候,把要校验的数据(字典:前端传过来的)传过来
-ser=BookSerializer(data=request.data)
-ser.is_valid()
-显示中文:error_messages={'required': '该字段必填'}
-局部钩子函数(value就是这个字段的值)
-def validate_字段名(self, value):
from django.shortcuts import render, HttpResponse
from app01.mySer import BookSerializer
from django.http import JsonResponse
from app01 import models
# Create your views here.
from rest_framework.views import APIView
class Books(APIView):
def get(self, request, *args, **kwargs):
ret = models.Book.objects.all()
# 生成一个序列化的对象,传参数
# 序列化多条,记住many=True
book_ser = BookSerializer(ret, many=True, context={'request': request})
print(book_ser.data)
return JsonResponse(book_ser.data, safe=False)
def post(self, request, *args, **kwargs):
# 前端传递过来的数据从data中取
# 用序列化类的数据校验
# data参数,是要校验的数据
response = {'status': 100, 'msg': '成功'}
ser = BookSerializer(data=request.data)
if ser.is_valid():
# 如果数据校验通过,is_valid是True
# 保存到数据库,ser是谁的对象?继承了ModelSerializer的类的对象
ser.save()
else:
response['status'] = 101
response['msg'] = ser.errors
return JsonResponse(response, safe=False)
from rest_framework import exceptions
class Auth():
def authenticate(self, request):
# 包装后的request对象,请求来的所有东西都能拿出来
# 如果认证通过,需要返回东西,如果认证不通过,要抛异常
token=request.GET.get('token')
ret=models.UserToken.objects.filter(token=token).first()
#如果有值,说明登录过了,而且带的随机字符串也是正确的
if ret:
return None
else:
# 如果没有值,抛异常
raise exceptions.APIException('您没有登录')
from rest_framework.request import Request
class BooksDetail(APIView):
authentication_classes = [Auth, ]
def get(self, request, pk):
response = {'status': 100, 'msg': '成功'}
ret = models.Book.objects.all().filter(pk=pk).first()
# 生成一个序列化的对象,传参数
# 序列化单,记住many=False
if ret:
book_ser = BookSerializer(ret, many=False)
print(book_ser.data)
response['data'] = book_ser.data
else:
response['status'] = 101
response['msg'] = '您查询的不存在'
return JsonResponse(response, safe=False)
def put(self, request, pk):
response = {'status': 100, 'msg': '成功'}
ret = models.Book.objects.all().filter(pk=pk).first()
if ret:
# 数据校验
# 传instance和不传instance,传instance的区别
# 不传instance,调save(),往数据库新增数据
# 传instance,调save(),修改数据
ser = BookSerializer(data=request.data, instance=ret)
if ser.is_valid():
# ret.name=request.data.get('name')
ser.save()
else:
response['status'] = 101
response['msg'] = ser.errors
else:
response['status'] = 102
response['msg'] = '修改的对象不存在'
return JsonResponse(response, safe=False)
class Publish(APIView):
def get(self, request, *args, **kwargs):
return HttpResponse('ok')
import uuid
class Login(APIView):
def post(self, request):
response={'status':100,'msg':'登录成功'}
name = request.data.get('name')
pwd = request.data.get('pwd')
user = models.UserInfo.objects.filter(name=name, pwd=pwd).first()
if not user:
response['status']=101
response['msg']='用户名或密码错误'
else:
# 生成一个随机字符串
token=uuid.uuid4()
# 去数据库保存
models.UserToken.objects.create(token=token,user=user)
response['token']=token
return JsonResponse(response,safe=False)