【问题标题】:docopt + schema validationdocopt + 模式验证
【发布时间】:2013-01-13 07:55:08
【问题描述】:

有没有更好的方法来处理这个验证:

#!/usr/bin/env python
""" command.

Usage:
  command start ID
  command finish ID FILE
  command (-h | --help)
  command (-v | --version)

Arguments:
  FILE     input file
  PATH     out directory

Options:
  -h --help     Show this screen.
  -v --version  Show version.
"""

from docopt import docopt
from schema import Schema, Use, SchemaError

if __name__ == '__main__':
    args = docopt(__doc__, version='command alpha')

    # Remove False or None keys from args dict
    for k, v in args.items():
        if (not v):
            args.pop(k)

    if 'start' in args:
        args.pop('start')
        schema = Schema({
            'FILE': Use(open, error='FILE should be readable'),
            'ID': Use(int, error='ID should be an int'),
        })
    elif 'finish' in args:
        args.pop('finish')
        schema = Schema({
            'FILE': Use(open, error='FILE should be readable'),
            'ID': Use(int, error='ID should be an int'),
        })

    try:
        args = schema.validate(args)
    except SchemaError as e:
        exit(e)

    print(args)

【问题讨论】:

    标签: python validation parsing schema docopt


    【解决方案1】:

    我会做以下事情:

    #!/usr/bin/env python
    """Command.
    
    Usage:
      command start ID
      command finish ID FILE
      command (-h | --help)
      command (-v | --version)
    
    Arguments:
      ID
      FILE     input file
    
    Options:
      -h --help     Show this screen.
      -v --version  Show version.
    
    """
    from docopt import docopt
    from schema import Schema, Use, Or, SchemaError
    
    if __name__ == '__main__':
        args = docopt(__doc__, version='command alpha')
    
        id_schema = Use(int, error='ID should be an int')
        file_schema = Or(None, Use(open, error='FILE should be readable'))
        try:
            args['ID'] = id_schema.validate(args['ID'])
            args['FILE'] = file_schema.validate(args['FILE'])
        except SchemaError as e:
            exit(e)
    
        print(args)
    

    虽然我希望 schema 可以使用单个模式而不是两个模式来表达相同的意思。我将尝试使将来能够制作如下架构:

    schema = Schema({'ID': Use(int, error='ID should be an int'),
                     'FILE': Or(None, Use(open, error='FILE should be readable')),
                     object: object})
    

    object: object 表示我只关心'ID''FILE',并且所有其他键/值都可以是任意对象。

    更新

    从 0.2.0 版开始,schema 现在可以正确处理这种情况了:

    schema = Schema({'ID': Use(int, error='ID should be an int'),
                     'FILE': Or(None, Use(open, error='FILE should be readable')),
                     object: object})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-27
      • 2012-05-02
      • 2012-03-29
      • 2011-06-02
      • 2011-06-08
      • 2019-02-16
      • 2010-11-22
      • 2011-06-30
      相关资源
      最近更新 更多