""" 知识点1:对于inspect包可以获取到函数的形参 import inspect signal = inspect.signature(arguments) param_dic = signal.parameters for key, value in param_dic.items(): # print(key, value) # print(type(key), type(value)) # print(key, value.name) # 默认 键 # print(key, value.default) # 默认 值 # print(key, value.annotation) # 类型 知识点2:装饰器 """ import inspect postman_body = { # "key": 66, # "name": "ws" } def separate_success_error(param_dic): """对校验结果进行分类""" status_success = "success" status_error = "error" # 有status 有value success_dic = {} error_dic = {} for key in param_dic: status = param_dic[key]["status"] value = param_dic[key]["value"] if status == status_success: success_dic[key] = value elif status == status_error: error_dic[key] = value else: assert "没有此类型" return success_dic, error_dic def pre(arguments, *args, **kwargs): """装饰器,就像fastapi里面的装饰器一样""" def decorate(): new_param_dic = {} signal = inspect.signature(arguments) param_dic = signal.parameters for key, value in param_dic.items(): key_name = value.name key_type = value.annotation key_default_value = value.default # 如果此时你不知道调用哪个方法你可以判断 key_value = deal_value_in_body(key_name, key_type, key_default_value, *args, **kwargs) new_param_dic[key_name] = key_value # 此时我们需要去看有没有错误的,如果有失败的,则只返回失败内容就好,如果没有则调用函数 data, error = separate_success_error(new_param_dic) if error: print(f"报错:{error}") assert "响应给页面错误信息" else: return arguments(**data) return decorate def deal_value_in_body(key_name=None, key_type=None, key_default_value=None, *args, **kwargs): # 从body里面去拿数据,然后在去返回value # 我们需要根据key_default_value去判断我们怎么对参数处理 response_dic = {"status": "error", "value": ""} if key_name == "...": if not (key_name in postman_body.keys()): response_dic["value"] = "this key is must" return response_dic value = postman_body.get(key_name) value = value if value else key_default_value if key_type: # 如果有type:则需要校验数据类型是否正确 if not isinstance(value, key_type): response_dic["value"] = f"this requirement a {key_type}" return response_dic # 如果有gt大于等于关键字,你也可以判断,我就不写了太懒了 response_dic["value"] = value response_dic["status"] = "success" return response_dic def my_Query(value): """fastapi里面的校验函数,名字不一样决定去哪里取数据""" # 这个函数只是为了告诉你,默认值是什么,懂了吗 return value # 这个就是装饰器, @pre # 路由处理函数 def main(key: int = my_Query(1000), name: str = my_Query(None)): print(f"key:{key}") print(f"name:{name}") if __name__ == '__main__': main()