gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:32:19 25 4
gpt4 key购买 nike

我想断言配置文件中存在某些值,但我不想让其他每一行都成为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 模式,但有 jsonschema在 PyPi 上可用。

用法相当简单。我在这里引用 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'

关于python - 干净地断言配置文件的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37507591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com