drf--part2
一、局部钩子和全局钩子
接上篇:
1、局部钩子
在反序列化校验中,我们不仅可以通过validators来自定义校验函数,也可以使用钩子函数来进行校验,首先我们介绍局部钩子。
局部钩子用在单个属性的校验,具体写法如下:
from rest_framework import serializers
class StudentSerializer(serializers.Serializer):
name = serializers.CharField(max_length=4)
age = serializers.IntegerField(max_value=80)
class_null = serializers.CharField()
description = serializers.CharField(allow_blank=True)
# 局部钩子如下:
def validate_name(self,val): #函数定义规则为:validate_(要校验属性)
if '777' in val:
raise serializers.ValidationError('数据校验未通过')
return val
接下来我们使用postman给接口发送post请求,并得到ok返回值:
我们接下来来看服务端响应结果:
如图,局部钩子生效。
2、全局钩子
全局钩子主要针对多个属性进行校验,写法如下:
from rest_framework import serializers
class StudentSerializer(serializers.Serializer):
name = serializers.CharField(max_length=4)
age = serializers.IntegerField(max_value=80)
class_null = serializers.CharField()
description = serializers.CharField(allow_blank=True)
# 全局钩子如下:
def validate(self,data): # data为post请求发送过来的有序字典数据
# 我们可以打印下data
print(data)
name = data.get('name')
description = data.get('description')
if name == description:
raise serializers.ValidationError('名字和简介不能相等')
return data
我们继续使用postman向接口发送post请求:
我们接下来来看服务端响应结果:
如图,全局钩子生效。
执行顺序:
1、执行is_valid()方法时,先校验序列化器中的所有属性field对应的规则
2、执行局部钩子
3、最后执行全局钩子
3、常用字段和参数
常用字段类型:
字段 | 字段构造方式 |
---|---|
BooleanField | BooleanField() |
NullBooleanField | NullBooleanField() |
CharField | CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) |
EmailField | EmailField(max_length=None, min_length=None, allow_blank=False) |
RegexField | RegexField(regex, max_length=None, min_length=None, allow_blank=False) |
SlugField | SlugField(maxlength=50, min_length=None, allow_blank=False) 正则字段,验证正则模式 [a-zA-Z0-9-]+ |
URLField | URLField(max_length=200, min_length=None, allow_blank=False) |
UUIDField | UUIDField(format=‘hex_verbose’) format: 1) 'hex_verbose' 如"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) 'hex' 如 "5ce0e9a55ffa654bcee01238041fb31a" 3)'int' - 如: "123456789012312313134124512351145145114" 4)'urn' 如: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 微软时间戳,通过微秒生成一个随机字符串 |
IPAddressField | IPAddressField(protocol=‘both’, unpack_ipv4=False, **options) |
IntegerField | IntegerField(max_value=None, min_value=None) |
FloatField | FloatField(max_value=None, min_value=None) |
DecimalField | DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位数 decimal_palces: 小数点位置 |
DateTimeField | DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None) |
DateField | DateField(format=api_settings.DATE_FORMAT, input_formats=None) |
TimeField | TimeField(format=api_settings.TIME_FORMAT, input_formats=None) |
DurationField | DurationField() |
ChoiceField | ChoiceField(choices) choices与Django的用法相同 |
MultipleChoiceField | MultipleChoiceField(choices) |
FileField | FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) |
ImageField | ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) |
ListField | ListField(child=, min_length=None, max_length=None) |
DictField | DictField(child=) |
选项参数:
参数名称 | 作用 |
---|---|
max_length | 最大长度 |
min_length | 最小长度 |
allow_blank | 是否允许为空 |
trim_whitespace | 是否截断空白字符 |
max_value | 最大值 |
min_value | 最小值 |
通用参数:
参数名称 | 说明 |
---|---|
read_only | 表明该字段仅用于序列化输出,默认False |
write_only | 表明该字段仅用于反序列化输入,默认False |
required | 表明该字段在反序列化时必须输入,默认True |
default | 反序列化时使用的默认值 |
allow_null | 表明该字段是否允许传入None,默认False |
validators | 该字段使用的验证器 |
error_messages | 包含错误编号与错误信息的字典 |
label | 用于HTML展示API页面时,显示的字段名称 |
help_text | 用于HTML展示API页面时,显示的字段帮助提示信息 |
二、视图相关
我们需要通过视图函数来进行数据库的操作
1、保存数据
方法一:
将校验通过的数据提交至数据库,我们可以通过is_valid()来进行判断,再用orm将数据写入数据库:
from django.shortcuts import render,HttpResponse
from student01.models import Student
from .serializers import StudentSerializer
from django.http import JsonResponse
from django.views import View
# Create your views here.
class StudentView(View):
def post(self,request):
data=request.POST
ser = StudentSerializer(data=data)
print(ser.is_valid())
#校验判断,校验成功将数据写入数据库,校验失败返回给错误提示
if ser.is_valid():
obj=Student.objects.create(
**ser.validated_data
)
serializer=StudentSerializer(instance=obj)
return JsonResponse(serializer.data,safe=False,json_dumps_params={'ensure_ascii':False})
else:
return JsonResponse({'error':'有字段错误'})
使用postman来进行测试:
我们还是使用之前的校验规则,先发送一个非法数据:
可以看到,成功返回了错误信息。
接下来我们发送一条合法数据:
接下来我们在数据库中验证数据是否被成功写入:
如图,成功写入数据。
方式二:
在序列器中定义create方法来保存数据:
serializers.py:
from rest_framework import serializers
from student01 import models
class StudentSerializer(serializers.Serializer):
name = serializers.CharField(max_length=4)
age = serializers.IntegerField(max_value=80)
class_null = serializers.CharField()
description = serializers.CharField(allow_blank=True)
# 全局钩子如下:
def validate(self,data): # data为post请求发送过来的有序字典数据
# 我们可以打印下data
print(data)
name = data.get('name')
description = data.get('description')
if name == description:
raise serializers.ValidationError('名字和简介不能相等')
return data
# 定义create方法
def create(self, validated_data):
obj=models.Student.objects.create(
**validated_data
)
return obj
views.py:
from django.shortcuts import render,HttpResponse
from student01.models import Student
from .serializers import StudentSerializer
from django.http import JsonResponse
from django.views import View
# Create your views here.
class StudentView(View):
def post(self,request):
data=request.POST
ser = StudentSerializer(data=data)
print(ser.is_valid())
#校验判断,校验成功将数据写入数据库,校验失败返回给错误提示
if ser.is_valid():
# =通过save触发序列化器中的create方法
instance = ser.save()
serializer=StudentSerializer(instance=instance)
return JsonResponse(serializer.data,safe=False,json_dumps_params={'ensure_ascii':False})
else:
return JsonResponse({'error':'有字段错误'})
我们用postman来进行测试:
成功拿到返回的数据,接下来我们去数据库验证:
数据成功写入!
2、更新数据
更新数据视图文件中需使用put方法,必须写instance,序列化器中需定义update方法,具体写法如下:
serializers.py:
from rest_framework import serializers
from student01 import models
class StudentSerializer(serializers.Serializer):
name = serializers.CharField(max_length=4)
age = serializers.IntegerField(max_value=80)
class_null = serializers.CharField()
description = serializers.CharField(allow_blank=True)
# 全局钩子如下:
def validate(self,data): # data为post请求发送过来的有序字典数据
# 我们可以打印下data
print(data)
name = data.get('name')
description = data.get('description')
if name == description:
raise serializers.ValidationError('名字和简介不能相等')
return data
# 定义create方法
def create(self, validated_data):
obj=models.Student.objects.create(
**validated_data
)
return obj
# 更新数据,定义update方法
def update(self, instance, validated_data):
print(validated_data['name'])
instance.name=validated_data['name']
instance.age=validated_data['age']
instance.class_null=validated_data['class_null']
instance.description=validated_data['description']
instance.save()
return instance
views.py:
from django.shortcuts import render,HttpResponse
from student01.models import Student
from .serializers import StudentSerializer
from django.http import JsonResponse
from django.views import View
from django.http.request import QueryDict
# Create your views here.
class StudentView(View):
def post(self,request):
data=request.POST
ser = StudentSerializer(data=data)
print(ser.is_valid())
#校验判断,校验成功将数据写入数据库,校验失败返回给错误提示
if ser.is_valid():
# =通过save触发序列化器中的create方法
instance = ser.save()
serializer=StudentSerializer(instance=instance)
return JsonResponse(serializer.data,safe=False,json_dumps_params={'ensure_ascii':False})
else:
return JsonResponse({'error':'有字段错误'})
def put(self,request):
ret=QueryDict(request.body)
data={
'id':ret.get('id'),
'name':ret.get('name'),
'age':ret.get('age'),
'class_null':ret.get('class_null'),
'description':ret.get('description')
}
ret1=Student.objects.get(id=data.get('id'))
ret2=StudentSerializer(instance=ret1,data=data)
if ret2.is_valid():
ret2.save()
return HttpResponse('ok')
else:
return JsonResponse({'error':'有字段错误'})
postman传入一组数据测试:
数据库中查看更新结果:
三、modelSerializer的使用
read-only:序列化时序列化出该字段数据,反序列化时不校验这个数据
write-only:序列化时不序列化这个字段数据,反序列化时需客户端传递这个数据进行校验
partial:只需要校验传入给序列化器的数据,适用于部分数据更新
序列化器serializers.py:
from rest_framework import serializers
from student01 import models
class StudentModelSerializer(serializers.ModelSerializer):
class Meta:
model=models.Student
fields='__all__'
extra_kwargs={
'id':{'read_only':True},
'age':{'write_only':True}
}
views.py:
from django.shortcuts import render
from django.http import JsonResponse
# Create your views here.
from django.views import View
from .serializers import StudentModelSerializer
from student01 import models
class StudentView(View):
def get(self,request):
all = models.Student.objects.all()
serializers=StudentModelSerializer(instance=all,many=True)
return JsonResponse(serializers.data,safe=False,json_dumps_params={'ensure_ascii':False})
def post(self,request):
data=request.POST
serializers=StudentModelSerializer(data=data)
if serializers.is_valid():
serializers.save() #能够自动帮我们保存数据,不用在序列化器中创建create方法
return JsonResponse({'info':'数据保存成功!'})
else:
return JsonResponse({'error':'非法数据!'})
我们使用postman进行测试:
我们在数据库查看执行结果:
如图,数据成功写入
四、响应状态码
写法:
from rest_framework import status
# return Response({'xx':'xxxxx'}, status=201)
return Response({'xx':'xxxxx'}, status=status.HTTP_201_CREATED)
所有状态码:
HTTP_100_CONTINUE = 100
HTTP_101_SWITCHING_PROTOCOLS = 101
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_202_ACCEPTED = 202
HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203
HTTP_204_NO_CONTENT = 204
HTTP_205_RESET_CONTENT = 205
HTTP_206_PARTIAL_CONTENT = 206
HTTP_207_MULTI_STATUS = 207
HTTP_208_ALREADY_REPORTED = 208
HTTP_226_IM_USED = 226
HTTP_300_MULTIPLE_CHOICES = 300
HTTP_301_MOVED_PERMANENTLY = 301
HTTP_302_FOUND = 302
HTTP_303_SEE_OTHER = 303
HTTP_304_NOT_MODIFIED = 304
HTTP_305_USE_PROXY = 305
HTTP_306_RESERVED = 306
HTTP_307_TEMPORARY_REDIRECT = 307
HTTP_308_PERMANENT_REDIRECT = 308
HTTP_400_BAD_REQUEST = 400
HTTP_401_UNAUTHORIZED = 401
HTTP_402_PAYMENT_REQUIRED = 402
HTTP_403_FORBIDDEN = 403
HTTP_404_NOT_FOUND = 404
HTTP_405_METHOD_NOT_ALLOWED = 405
HTTP_406_NOT_ACCEPTABLE = 406
HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407
HTTP_408_REQUEST_TIMEOUT = 408
HTTP_409_CONFLICT = 409
HTTP_410_GONE = 410
HTTP_411_LENGTH_REQUIRED = 411
HTTP_412_PRECONDITION_FAILED = 412
HTTP_413_REQUEST_ENTITY_TOO_LARGE = 413
HTTP_414_REQUEST_URI_TOO_LONG = 414
HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416
HTTP_417_EXPECTATION_FAILED = 417
HTTP_418_IM_A_TEAPOT = 418
HTTP_422_UNPROCESSABLE_ENTITY = 422
HTTP_423_LOCKED = 423
HTTP_424_FAILED_DEPENDENCY = 424
HTTP_426_UPGRADE_REQUIRED = 426
HTTP_428_PRECONDITION_REQUIRED = 428
HTTP_429_TOO_MANY_REQUESTS = 429
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451
HTTP_500_INTERNAL_SERVER_ERROR = 500
HTTP_501_NOT_IMPLEMENTED = 501
HTTP_502_BAD_GATEWAY = 502
HTTP_503_SERVICE_UNAVAILABLE = 503
HTTP_504_GATEWAY_TIMEOUT = 504
HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505
HTTP_506_VARIANT_ALSO_NEGOTIATES = 506
HTTP_507_INSUFFICIENT_STORAGE = 507
HTTP_508_LOOP_DETECTED = 508
HTTP_509_BANDWIDTH_LIMIT_EXCEEDED = 509
HTTP_510_NOT_EXTENDED = 510
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511
本文地址:https://blog.csdn.net/qq_39787513/article/details/109246767
下一篇: 京东个人信息怎么修改?
推荐阅读