voluptuousを使用してデータを検証する

5088 ワード

  Python  ,             ,          ,      if  ,           ,            ,        ,        ,   ,                 。
         ,             python      lib,   voluptuous。        ,                 ,      。             voluptuous     。

voluptuous , , , pip 。 0.8.8: pip install voluptuous==0.8.8 voluptuous , , , json ,json python (dict), 。 , , , , , q , per_page , page 。 , voluptuous , : from voluptuous import Schema s = Schema({ 'q': str, 'per_page': int, 'page': int }) : q , per_page , page 。 , , : {"q": "hello", "page": 10, "per_page": 20 } , ? : from voluptuous import Schema s = Schema({ 'q': str, 'per_page': int, 'page': int }) print s({"q": "hello", "page": 10, "per_page": 20 }) , , , , , : {"q": "hello", "page": 10, "per_page": 20 } , voluptuous 。 。 , , , , : {"q": "hello", "page": "world", "per_page": 20 } , , , ,Schema , , : try: print s({"q": "hello", "page": "world","per_page": 20}) except MultipleInvalid as e: print "error: {} occur while parse args".format(e.errors) , : error: [TypeInvalid('expected int',)] occur while parse args , 。 ok, , , , , 。 ? , , Required , : from voluptuous import Schema, Required required_s = Schema({ Required('q'): str, 'per_page': int, 'page': int }) , , : try: print required_s({}) except MultipleInvalid as e: print "error: {} occur while parse with required args".format(e.errors) , , : error: [RequiredFieldInvalid('required key not provided',)] occur while parse with required args , , , , , , ? , , Schema , extras, : not_allow_extra_s = Schema({ 'q': str, 'per_page': int, 'page': int }, extra=False) : try: print not_allow_extra_s({"q": "hello", "unknown": "key"}) except MultipleInvalid as e: print "error: {} occur while parse with no extras args".format(e.errors) : error: [Invalid('extra keys not allowed',)] occur while parse with no extras args ,Schema , , True, 。 , , , , 10 , ? 10 str : def less_than_10(value): if isinstance(value, str) and len(value) , , , , , Invalid 。 Schema 。 , , ? , 。 , ,Schema , Schema 。 , ? , , , 。 , , , , , , , : def convert_letter(value): if isinstance(value, str): return value.upper() raise Invalid("not valid string") transformation_s = Schema({ Required('q'): convert_letter, 'per_page': int, 'page': int }) print transformation_s({'q': 'hello'}) , : {'q': 'HELLO'} 。 , voluptuous , , 。