干净地断言配置文件的特定部分
Cleanly asserting a specific part of a config file
我想 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"
}
确保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'
我想 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"
}
确保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'