我想assert
我的配置文件中存在某些值,但我不想让所有其他行都成为assert
语句。有更清洁的方法吗?
assert config["email"]["address"], "You must supply email information."
assert config["email"]["address"], "You must supply an address to receive."
self.addresses = config["email"]["address"]
self.smtpserver = config.get["email"].get("smtpserver", "smtp.gmail.com:587")
assert config["email"]["sender"], "You must a sender for your email."
self.sender = config["email"]["sender"]
assert config["email"]["password"], "You must supply an email password"
self.password = config["email"]["password"]
配置:
"email": {
"address": [
"someone@place.potato"
],
"smtpserver": "smtp.potato.com:567",
"sender": "someoneelse@place.potato",
"password": "sup3rg00dp455w0rd"
}
答案 0 :(得分:1)
确保JSON数据符合特定格式的典型方法是使用JSON Schema。
虽然Python没有内置包来处理JSON模式,但PyPi上有jsonschema
。
用法非常简单。我在这里引用PyPi的样本:
from jsonschema import validate
schema = {
"type" : "object",
"properties" : {
"price" : {"type" : "number"},
"name" : {"type" : "string"},
},
}
# If no exception is raised by validate(), the instance is valid.
validate({"name" : "Eggs", "price" : 34.99}, schema)
validate({"name" : "Eggs", "price" : "Invalid"}, schema)
Traceback (most recent call last):
...
ValidationError: 'Invalid' is not of type 'number'