干净地断言配置文件的特定部分

时间:2016-05-29 08:04:28

标签: python python-3.x assert python-3.5

我想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"
  }

1 个答案:

答案 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'