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