python - docopt + 模式验证

标签 python validation parsing schema docopt

是否有更好的方法来处理此验证:

#!/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)

最佳答案

我会做以下事情:

#!/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})

by 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})

关于python - docopt + 模式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14588098/

相关文章:

html - 验证错误 : Element a not allowed as child of element ul in this context.(抑制来自该子树的更多错误。)

html - 根据 W3C,使用 Google 字体 : however, 代码不是有效的 HTML5?

python - 使用 M2Crypto 在 pem 文件中保存和加载 X509 证书

python - nltk 标记化和收缩

python - 找出还有谁在引用,大数据

python - 如何在 Python 中使用线程?

javascript - 信用卡验证无法在 Wordpress 中运行

regex - 解析源代码中的注释和字符串

python - 在 Python 中实现 "rules engine"

c++ - 如何将字符串解析为 std::map 并验证其格式?