5

有没有办法使用 voluptuous 来定义条件规则?

这是我的架构:

from voluptuous import Schema, All, Any

schema = Schema({
    'resolution': All(str, Any('1920x1080', '1280x720')),
    'bitrate': 20,
})

没关系,但现在我想根据分辨率值验证比特率值。如果我有1920x1080分辨率,那么我需要确保比特率是以下值之一:20、16、12、8;然后1280x720比特率应该是以下之一:10、8、6、4。

我怎样才能做到这一点?该项目的 github 页面上有信息,但我在那里找不到我的案例。

4

2 回答 2

8

我对类似问题的解决方案是做类似的事情

from voluptuous import Schema, Any

lo_res = Schema({'resolution': '1280x720', 'bitrate': Any(10, 8, 6, 4)})
hi_res = Schema({'resolution': '1920x1080', 'bitrate': Any(20, 16, 12, 8)})
schema = Any(lo_res, hi_res)

这将为您提供适当的验证,尽管错误消息可能有点神秘。您可以编写更加自定义的 Any 版本来改进错误消息。

于 2014-12-23T08:29:21.857 回答
5

Voluptuous supports custom validation functions [1], but they only receive as input parameter the value being currently validated, not any other previously validated values. This means trying to do something like 'bitrate': (lambda bitrate, resolution: Any(20, 16, 12, 8) if bitrate in (...) else Any (10, 8, 6, 4)) will unfortunately not work.

You can try using 'bitrate': Any(20, 16, 12, 10, 8, 6, 4) and then performing secondary validation yourself to make sure it's consistent with resolution.

Another approach could be to write a validator function for the complete dictionary, where the function would check both resolution and bitrate at the same time, though this way you'd be writing some code you normally get for free from voluptuous.

[1] https://github.com/alecthomas/voluptuous#validation-functions

于 2014-06-14T17:35:41.637 回答