กำหนดโครงสร้างไฟล์การกำหนดค่าได้อย่างง่ายดายและตรวจสอบไฟล์โดยใช้เทมเพลต -
Validit ถูกทดสอบใน Cpython 3.6, 3.7, 3.8 และ 3.9 เพียงติดตั้งโดยใช้ PIP:
$ (sudo) pip install validit โดยค่าเริ่มต้น ValIDIT รองรับไฟล์การกำหนดค่า JSON เท่านั้นหรือข้อมูลที่โหลดแล้ว (ไม่ใช่โดยตรงจากไฟล์กำหนดค่า) อย่างไรก็ตามการใช้การพึ่งพาเพิ่มเติม ValidIt รองรับรูปแบบไฟล์ต่อไปนี้:
JSONYAMLTOMLในการติดตั้ง Validit ด้วยการพึ่งพาที่จำเป็นเพิ่มเติมเพื่อรองรับรูปแบบไฟล์ที่คุณต้องการใช้:
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 Validit ยังอยู่ระหว่างการพัฒนาที่ใช้งานอยู่และคุณสมบัติหลักบางอย่างอาจเปลี่ยนแปลงได้อย่างมากในอนาคตอันใกล้
หากคุณวางแผนที่จะใช้ ValidIt เป็นการพึ่งพาโครงการของคุณเราขอแนะนำให้ระบุโมดูลที่แน่นอนที่คุณใช้ในไฟล์ requirements.txt หรือ setup.py scripts
ตัวอย่างเช่นการระบุเวอร์ชัน v1.3.2 ใช้บรรทัดต่อไปนี้ในไฟล์ requirements.txt ของคุณ. txt:
validit==1.3.2
validit[yaml]==1.3.2 # If using extra file formats