2016-05-29 9 views
1

assert私の設定ファイルに特定の値が存在するようにしたいのですが、1行おきに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": [ 
     "[email protected]" 
    ], 
    "smtpserver": "smtp.potato.com:567", 
    "sender": "[email protected]", 
    "password": "sup3rg00dp455w0rd" 
    } 

答えて

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' 
関連する問題