def validate_field_value(field, value, stringify=False): """ 校验字段的值,并返回其类型的值 """ # 1. 获取类型的实例 instance = get_instance(field.type, field.option) if not instance: return ValueError('校验字段的值出错:未找到类型实例') # 2. 获取校验后的值 if stringify: v = instance.stringify(value=value) else: v = instance.destringify(value=value) # 3. 对多值进行判断 # if field.unique: # value = Value.objects.filter(field=field, value=str(v)).first() # if value: # raise ValueError('值为"{}"已经存在,需要唯一'.format(v)) # 最后返回校验后的值 return v
import json from cmdb.types import get_instance jsonstr = """ { "1":"cmdb.types.Int", "2":"200", "option":{ "max":100, "min":1 } } """ obj = json.loads(jsonstr) type = obj["1"] option = obj["option"] print(get_instance(type, **option).stringfy(obj["2"]))
"value":1000, "options":{ "max":100000, "min":0 } } ''' ipjsonstr = '''{ "types":"cmdb.types.IP", "value":"192.168.1.1", "options":{ "prefix":"192.1" } } ''' obj = json.loads(jsonstr) print(obj) #返回字典 type = obj["types"] value = obj["value"] options = obj["options"] int = get_instance(type, **options) #解构 max:10000 min:0 print(int.stringfiy(value)) ipobj = json.loads(ipjsonstr) type = ipobj["types"] value = ipobj["value"] options = ipobj["options"] print("-------------", options) ip = get_instance(type, **options) print(ip.stringfiy(value))
import logging from cmdb.types import Int, get_instance, inject_classes_cache from cmdb.utils import getlogger jsonstr = """ { "type":"cmdb.types.IP", "value":"172.1.0.1", "option":{ "prefix":"172.1" } } """ obj = json.loads(jsonstr) print(obj) inject_classes_cache() # 函数调用放在模块后面 print(get_instance(obj['type'], **obj['option']).stringify(obj['value'])) print(get_instance(obj['type'], **obj['option']).stringify(obj['value'])) def a(): logger = getlogger(__name__, '/Users/quyixiao/ttg/test.log') # 路径自行更换 logger.info('...................xxxxxxxxxxxxxxxxxxx') a()