1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import json
body = { "id": "12", "url": "https://gitee.com/yooke/User.git", "type": "c", }
body = json.dumps(body)
class Argument: def __init__(self, key, required=True, filter=None, type=None, help=None): self.key = key self.required = required self.filter = filter self.type = type self.help = help
class Parser: def __init__(self, *arguments): self.arguments = arguments
def parse(self, data): form, error = {}, None for arg in self.arguments: value = data.get(arg.key) if arg.required and value is None: error = arg.help break if arg.type: if not isinstance(value, arg.type): try: value = arg.type(value) except ValueError: error = arg.help break if arg.filter and not arg.filter(value): error = arg.help break form[arg.key] = value return form, error
class JSONParser(Parser): def parse(self, data): data = json.loads(data) return super().parse(data)
class XMLParser(Parser): def xmltodict(self, data): return data
def parse(self, data): data = self.xmltodict(data) return super().parse(data)
def main(): form, error = JSONParser( Argument('id', type=int, help='ID必须是整数'), Argument('name', required=False, help='name参数必填'), Argument('url', help='url参数必填'), Argument('type', filter=lambda x: x in ('a', 'b', 'c'), help='type参数必须是a,b,c中的一个'), ).parse(body) if error is None: print('参数校验通过: ', form) else: print('参数校验失败: ', error)
main()
|