In the Python back-end world, validating the parameters of a front-end request is often a tedious task. After investigating a series of open source frameworks, I did not find a lightweight and convenient solution, so I developed pyVali and basically achieved the expected goal. Readers can install pyVali through PIP Install.
The brief usage is as follows:
from pyVali import Int, Float, Str, Dict, List
value = {
"user_id": "32495732"."score": 3.5."telephone": "13234566543"."user_type": 2."question_list": [{
"question_id": "asdfsdf"."question": "Hello?"."answer": "I'm fine. Who are you?"."status": 0,
}]
}
schema = Dict({
"user_id": Int(comment="User id",),"score": Float(comment="User rating", min_value=0, max_value=5),
"telephone": Str(comment="Subscriber's Phone Number", min_length=11,
max_length=11, pattern=r"^1[3456789]\d{9}$"),
"user_type": Int(comment="User Type", enum=[0, 1, 2, 3]),
"question_list": List(
struct=[Dict(
{"question_id": Str(comment="The question id"),
"question": Str(comment="Problem"),
"answer": Str(comment="Answer"),
"status": Int(comment="State")},
comment="Problem")],
comment="List of Questions", )
})
errMsg, value = schema.validate(value)
if errMsg:
raise Exception(errMsg)
print(errMsg, value)
Copy the code