validit
v1.3.2
轻松定义配置文件结构,并使用模板验证文件。 ?
在Cpython 3.6、3.7、3.8和3.9上测试了验证。只需使用PIP安装:
$ (sudo) pip install validit默认情况下,验证仅支持JSON配置文件或已经加载的数据(不是直接来自配置文件)。但是,使用其他依赖项,验证支持以下文件格式:
JSONYAMLTOML要安装验证额的额外所需依赖项以支持您的首选文件格式,请使用:
pip install validit[yaml] # install dependencies for yaml files
pip install validit[toml] # toml files
pip install validit[json,toml] # json and toml files
pip install validit[all] # all available file formats 要创建模板,您将需要基本的Template模块,通常是其他三个基本模块的TemplateList , TemplateDict和Optional 。
在下面的示例中,我们将创建一个代表单个用户的基本模板:
from validit import Template , TemplateList , TemplateDict , Optional
TemplateUser = TemplateDict ( # a dictionary with 2 required values
username = Template ( str ), # username must be a string
passcode = Template ( int , str ), # can be a string or an integer.
nickname = Optional ( Template ( str )), # optional - if provided, must be a string.
)为了使用模板验证数据,您应该使用Validate对象。
from validit import Template , TemplateDict , Optional , Validate
template = TemplateDict (
username = Template ( str ),
passcode = Template ( int , str ),
nickname = Optional ( Template ( str )),
)
data = {
'username' : 'RealA10N' ,
'passcode' : 123 ,
}
valid = Validate ( template , data )
if valid . errors : # if one or more errors found
print ( valid . errors ) # print errors to console
exit ( 1 ) # exit the script with exit code 1
else : # if data matches the template
run_script ( valid . data ) # run the script with the loaded data 如果您的数据存储在文件中,则可以使用ValidateFromJSON , ValidateFromYAML或ValidateFromTOML对象:
from validit import Template , TemplateDict , Optional , ValidateFromYAML
filepath = '/path/to/data.yaml'
template = TemplateDict (
username = Template ( str ),
passcode = Template ( int , str ),
nickname = Optional ( Template ( str )),
)
with open ( filepath , 'r' ) as file :
# load and validate data from the file
valid = ValidateFromYAML ( file , template )
if valid . errors : # if one or more errors found
print ( valid . errors ) # print errors to console
exit ( 1 ) # exit the script with exit code 1
else : # if data matches the template
run_script ( valid . data ) # run the script with the loaded data 验证仍处于积极的发展状态,在不久的将来,某些核心功能可能会发生重大变化。
如果您打算将验证用作项目的依赖性,我们强烈建议您在requirements.txt文件或setup.py脚本中指定您使用的模块的确切版本。
例如,要查明版本v1.3.2使用您的requirements.txt中的以下行。txt文件:
validit==1.3.2
validit[yaml]==1.3.2 # If using extra file formats