2023-04-10 02:57:44 +00:00
|
|
|
from rest_framework import serializers
|
|
|
|
|
|
|
|
example_info = [
|
2023-04-13 11:02:04 +00:00
|
|
|
{"name": "name", "label": "姓名", "required": False, "default": "广州老广", "type": "str"},
|
2023-04-10 02:57:44 +00:00
|
|
|
{"name": "age", "label": "年龄", "required": False, "default": 18, "type": "int"},
|
|
|
|
]
|
|
|
|
|
|
|
|
type_field_map = {
|
|
|
|
"str": serializers.CharField,
|
2023-04-21 03:18:04 +00:00
|
|
|
"password": serializers.CharField,
|
2023-04-10 02:57:44 +00:00
|
|
|
"int": serializers.IntegerField,
|
|
|
|
"bool": serializers.BooleanField,
|
|
|
|
"text": serializers.CharField,
|
|
|
|
"choice": serializers.ChoiceField,
|
2023-04-11 11:27:52 +00:00
|
|
|
"list": serializers.ListField,
|
2023-04-10 02:57:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def set_default_if_need(data, i):
|
|
|
|
field_name = data.pop('name', 'Attr{}'.format(i + 1))
|
|
|
|
data['name'] = field_name
|
|
|
|
|
|
|
|
if not data.get('label'):
|
|
|
|
data['label'] = field_name
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
|
|
def set_default_by_type(tp, data, field_info):
|
|
|
|
if tp == 'str':
|
|
|
|
data['max_length'] = 4096
|
2023-04-21 03:18:04 +00:00
|
|
|
elif tp == 'password':
|
|
|
|
data['write_only'] = True
|
2023-04-10 02:57:44 +00:00
|
|
|
elif tp == 'choice':
|
|
|
|
choices = field_info.pop('choices', [])
|
|
|
|
if isinstance(choices, str):
|
|
|
|
choices = choices.split(',')
|
|
|
|
choices = [
|
|
|
|
(c, c.title()) if not isinstance(c, (tuple, list)) else c
|
|
|
|
for c in choices
|
|
|
|
]
|
|
|
|
data['choices'] = choices
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
|
|
def create_serializer_class(serializer_name, fields_info):
|
|
|
|
serializer_fields = {}
|
2023-06-16 07:07:17 +00:00
|
|
|
fields_name = ['name', 'label', 'default', 'required', 'type', 'help_text']
|
2023-04-10 02:57:44 +00:00
|
|
|
|
|
|
|
for i, field_info in enumerate(fields_info):
|
|
|
|
data = {k: field_info.get(k) for k in fields_name}
|
|
|
|
field_type = data.pop('type', 'str')
|
2023-06-15 05:14:02 +00:00
|
|
|
|
2023-06-16 07:07:17 +00:00
|
|
|
# 用户定义 default 和 required 可能会冲突, 所以要处理一下
|
|
|
|
default = data.get('default', '')
|
|
|
|
if default not in ['', None]:
|
|
|
|
data['required'] = False
|
|
|
|
else:
|
2023-06-15 05:14:02 +00:00
|
|
|
data.pop('default', None)
|
2023-06-16 07:07:17 +00:00
|
|
|
data['required'] = True
|
2023-04-10 02:57:44 +00:00
|
|
|
data = set_default_by_type(field_type, data, field_info)
|
|
|
|
data = set_default_if_need(data, i)
|
|
|
|
field_name = data.pop('name')
|
|
|
|
field_class = type_field_map.get(field_type, serializers.CharField)
|
|
|
|
serializer_fields[field_name] = field_class(**data)
|
|
|
|
return type(serializer_name, (serializers.Serializer,), serializer_fields)
|