DRF view Features (2)

This post was last made Jiege, I will take you to the editor 2018-12-20 13:22

Django REST Framework (DRF)
D: Framework for building Web API is a powerful and flexible, based on secondary development framework Django
E :
① provide definitions serializer serializer method according ORM or other automatic serialization or deserialization
provided ② abundant class view, Mixin extension class set of views, to facilitate view
③ rich customization level: automatically generate the API
④ authentication, certification authority, limiting the system
⑤ intuitive API web interface
⑥ scalability, plug-rich
U:
① need Python and Django
② installation DRF: PIP install djangorestframework
③ add rest_framework application: settings.py add INSTALLED_APPS 'rest_framework' .
④ create a serializer: Write in serializers.py, inherited many types serializer, relevant attributes method
to write ⑤ view: APIView, ModelMixin, Viewset
⑥ defined routes: create a route object registration view set, add the information to the router django route list
⑦ start: python manage.py runserver, there is a corresponding API Web browser page

serializer (the serializer)
1. custom type, inheritance rest_framework.serializers.Serializer
2. The model types, inheritance rest_framework.serializers.ModelSerializer

serializer fields and options type
commonly used field types :
Field
Field construction way
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 (max length = 50, min_length = None, allow_blank = False)
regular field, to verify normal mode [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_lenght
最小长度
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页面时,显示的字段帮助提示信息


创建Serializer对象
构造方法:Serializer(instance=None, data=empty, **kwarg)
参数1,序列化必须传入的模型类对象
参数2,反序列化时把数据传入data
额外参数:例如context={'XX':'XX'},可通过context属性获取

序列化注意点:
1. 序列化时如果被序列化是多条查询集,通过添加many=True,列表形式
如果关联对象有多个,也可以在序列化器字段添加many=True
2. 如果模型类存在外键字段,处理方式如下:
①PrimaryKeyRelatedField,需设置read_only=True或queryser参数
被序列化后是关联字段数据
②StringRelatedField,被序列化是关联对象__str__返回值
③HyperlinkedRelatedField,需设置read_only,view_name
被序列化为关联对象数据的API链接
④SlugRelateField,需设置read_only,slug_field
被序列化后是关联对象的指定字段数据
⑤使用关联对象的序列化器类的实例
⑥重写to_representation 可修改被序列化后的返回值

反序列化
验证:在反序列化时,对数据验证,验证成功后才可获取数据或保存为模型类对象
①调用is_valid方法验证,成功True,失败False
②验证失败时,通过序列化器对象的errors属性获取错误信息,返回字典包含字段和字段错误,如果非字段错误,可修改配置中NON_FIELD_ERRORS_KEY来控制键名
③验证成功时,通过序列化器对象的validated_date属性获取数据
注意点: 带参数raise_exception=True在反序列化时is_valid()方法在验证失败时抛出serializers.ValidationError,REST framework接收到此异常,会向前端返回HTTP 400 Bad Request响应。

自定义验证行为:
1. validate_字段名:在序列化器中添加方法,方法名validate_字段名,参数为value,对value做校验,raise serializers.ValidationError('XXXX'),返回值value
2. validate:在序列化器中添加validate方法,可同时对多个字段进行验证
参数为attrs,从attrs中获取值,然后进行逻辑处理,抛出异常,返回值attrs
3.validator:在序列化器上方编写函数,参数value,对value校验,抛出异常
在序列化器字段中加入validator选项参数,为列表形式,值为函数名。
4. REST framework提供的validators:
UniqueValidator 单字段唯一:字段中设置,参数为queryset
UniqueTogetherValidation联合唯一:class Meta中设置,参数queryset和fields

保存:如果验证成功,向基于validated_data完成数据对象的创建,可以通过create和update来实现
1.新建:在序列化器中重写create方法,参数为validate_data,
返回值为模型类.objects.create(**validated_data)
2.更新:在序列化器中重写update方法,参数instance即要更新的实例和validate_data
对validate_data字典获取其值,对无传递值给予默认值 instance.字段,并赋给instance.字段,然后调用instance.save()提交,返回值instance
注意点:
①实现了create和update方法后,在反序列化时既可以序列化对象.save()返回数据对象实例并保存或更新到数据库
②调用save时,如果有传instance实例,则调用update方法更新数据,否则调用create方法新建数据。
③调用save可传参,参数可从validated_data中获取
④如果没有传递所有required字段,会抛出验证异常,可通过使用partial=True实现部分字段更新

模型类序列化器ModelSerializer
D:可基于模型类自动生成一系列字段,会自动生成valiators和实现了默认的create和update方法
U:
class serializer (serializers.ModelSerializer): # here may be a custom field serializer
         class Meta -:               
                  Model # = model name of the class to which the model-based reference               
                  fields = '__all__' # represents all the fields, which fields can be specified, be tuple type ()               
                  the exclude = ( 'XX',) # excluded which fields are tuples               
                  depth = 1 # default associated master key may be generated simply nested, an integer representing the nested hierarchy               
                  read_only_fields = ( 'XX', ) # indicates read only field, i.e. field is only used to serialize the output               
                  extra_kwargs = {field: {option: value}} # option to add or amend parameters of nested dictionaries serializer field








Guess you like

Origin www.cnblogs.com/abdm-989/p/12003483.html