1

ConfigObjとValidatorを使用して、Pythonで構成ファイルを解析しています。このツールはとても気に入っていますが、configSpecファイルを使用した検証に問題があります。統制語彙から値を選択するように強制するoption()configSpecタイプを使用しています。

output_mode = option("Verbose", "Terse", "Silent")

ユーザーがCVにないオプションを入力したときにコードに知らせたい。私が好きなことから、Validatorはどの構成キーが検証に失敗したかだけを言っているようですが、なぜ失敗したのかはわかりません:

from configobj import ConfigObj, flatten_errors
from validate import Validator

config = ConfigObj('config.ini', configspec='configspec.ini')
validator = Validator()
results = config.validate(validator)

if results != True:
    for (section_list, key, _) in flatten_errors(config, results):
        if key is not None:
            print 'The "%s" key in the section "%s" failed validation' % (key, ', '.join(section_list))
        else:
            print 'The following section was missing:%s ' % ', '.join(section_list)

そのコードスニペットは機能しますが、キーが検証に失敗した理由は、整数範囲にないことからCVにないことまで、さまざまな理由があります。キー名を調べて、そのキーの失敗ケースに応じて別の種類の例外を発生させる必要はありません。特定のタイプの検証エラーを処理するためのよりクリーンな方法はありますか?

長年のstackoverflowリーダー、初めてのポスター:-)

4

1 に答える 1

1

更新:これは私がやりたいことだと思います。重要なのは、config obj がエラーを例外として保存し、ValidateError をサブクラス化するエラーに対してチェックできることです。次に、パラメーター値ごとに 1 回のチェックではなく、サブクラスごとに 1 回のチェックを行うだけで済みます。検証が失敗した場合に検証が例外をスローした方が良いかもしれませんが、他の機能が失われる可能性があります。

self.config = configobj.ConfigObj(configFile, configspec=self.getConfigSpecFile())
validator = Validator()
results = self.config.validate(validator, preserve_errors=True)

for entry in flatten_errors(self.config, results):

   [sectionList, key, error] = entry
   if error == False:
      msg = "The parameter %s was not in the config file\n" % key
      msg += "Please check to make sure this parameter is present and there are no mis-spellings."
      raise ConfigException(msg)

   if key is not None:
      if isinstance(error, VdtValueError):
         optionString = self.config.configspec[key]
         msg = "The parameter %s was set to %s which is not one of the allowed values\n" % (key, self.config[key])
         msg += "Please set the value to be in %s" % optionString
         raise ConfigException(msg)

OptionString は単なるリストではなく、option("option 1", "option 2") という形式の文字列であるため、見栄えを良くするには、() 内の部分文字列を取得する必要があります。

于 2013-01-17T00:50:01.113 に答える