一个简单的依赖验证器
required的Python项目详细描述
必需:简单的多字段验证
Required是一个简单的库,它允许您验证依赖项 跨越多个领域。我们的目标是通过提供一种声明性的方式来编码验证逻辑,使表单、seralizer和函数等的编写更加容易。它的目标是:
- 使用声明性方式对验证逻辑进行编码
- 允许您轻松维护验证逻辑
- 允许您轻松重用验证逻辑 <> LI>与你想要验证的灵活
如果这听起来不错的话。继续读!
安装
使用pip
pip install required
快速启动
您可以通过多种方式使用Required。最简单的方法是使用validate
装饰器验证函数调用的输入。
fromrequiredimportvalidate@validatedefcalculate_sum(positive_number,negative_number):""" positive_number -> positive_number > 0 negative_number -> negative_number < 0 """returnpositive_number+negative_number# the following will raise a validation exceptioncalculate_sum(1,1)# this will pass validationcalculate_sum(1,-1)# 0
如果您想在docstring中包含其他信息,那么验证规则可以包装在Requires { }
中,如下所示:
@validatedefcalculate_sum(positive_number,negative_number):""" Other documentation relating to calculate_sum Requires { positive_number -> positive_number > 0 negative_number -> negative_number < 0 } You can also put information after the requires rules """returnpositive_number+negative_number
验证规则写在函数的doc字符串中。它们看起来像:
[param] -> [expression_1] [comparator] [expression_2]
当存在param
时,需要expression_1 [comparator] expression_2
求值为true。
最简单的表达式只是传递到函数中进行验证的变量,但是它们可能更复杂。更多的例子见食谱。
比较器可以是标准python比较器操作之一;==
、!=
、in
、>=
、<=
、>
、<
。
食谱
下面是一些编写验证规则的示例
# Arithmetic on the objects follow normal maths rules.
# you need to put brackets to define expressions
x -> (x + 1) < 1
x -> (x - y) == 1
# A value `x` needs to be in an array
x -> x in arr
# The length of x must be 10
# see section on registering functions
x -> len(x) == 10
# The length of x and y must be the same
x -> len(x) == len(y)
# when x is present y must not be present
# TODO: not implemented in DSL yet
x -> x == <empty>
# x must be equal to the return value of a function
x -> x == func(x)
# Partial dependencies can be also specified
# when x == 1 then y must be 2
x == 1 -> y == 2
# when x == 1 then y must be set
x == 1 -> y
注册可调用项
您可以将可调用项注册到验证范围中。当您希望调用普通的python内置项或自定义可调用项时,这非常有用。
fromrequiredimportvalidatescoped_validate=validate.register_callables({"len":len,"abs":abs})@scoped_validatedefreturn_first_element(arr):""" arr -> len(arr) >= 1 """returnarr[0]# validation scoped callables can also be nested# len, abs and my_func are available in the second_scoped_validate decoratorsecond_scoped_validate=scoped_validate.register_callables({"my_func":my_func})# or inserted at function level@validate(callable_dict={"new_func":new_func})defother_function(var):""" var -> new_func(var) >= 1 """returnvar
贡献
如果你想贡献你是最受欢迎的!这个项目是根据MIT许可证分发的。它使用tox对python 2.7和3.4+进行测试