保存されたコンフィグレーションファイルを読み込む際に、手軽さ故にconfigparserが使われるケースが多いと思う。シンプルなINIファイルを用意した。以前の投稿のスクリプトに流用可能なものにしよう。
開発環境:
Python 3.9.2
ファイル名をibconnect.iniとして保存した。
[gridmaster]
GM=192.168.3.51
USER=admin
PASS=infoblox
VER=v2.11.2
このiniファイルのキーや値のバリデーションは先送りにしてファイルを読み込んでキーと値を取り出す。
iniファイル内のオプション名が小文字に変換されないようにするにはConfigParserのメソッドであるoptionxformを上書きする。
>>> import configparser
>>>
>>> config = configparser.ConfigParser()
>>> config.read('ibconnect.ini')
['ibconnect.ini']
>>> attr = dict(config.items('gridmaster'))
>>>
>>> attr['gm'] # キーがLowercaseになってしまう
'192.168.3.51'
>>> attr
{'gm': '192.168.3.51', 'user': 'admin', 'pass': 'infoblox', 'ver': 'v2.11.2'}
>>> config = configparser.ConfigParser()
>>> # オプション名をLowercasへ変換するoptionxformを上書き
>>> config.optionxform = lambda option: option
>>> config.read('ibconnect.ini')
['ibconnect.ini']
>>> attr = dict(config.items('gridmaster'))
>>> attr
{'GM': '192.168.3.51', 'USER': 'admin', 'PASS': 'infoblox', 'VER': 'v2.11.2'}
>>>
以前の投稿の定数クラスへ今回のconfigparserを実装しよう。
import configparser
from metaconst import MetaConstant
config = configparser.ConfigParser()
config.optionxform = lambda option: option
config.read('ibconnect.ini')
attr = dict(config.items('gridmaster'))
attr['API'] = f'https://{attr["GM"]}/wapi/{attr["VER"]}/'
ibConst = MetaConstant('ibConst', (object,), attr) #クラス記法ではないがMetaConstantを継承したクラスを定義する
念の為、継承したメタクラスが機能しているか確認する。
>>> print(ibConst)
<class '__main__.ibConst'> #クラスとして認識されている
>>> ibConst.GM
'192.168.3.51'
>>> ibConst.USER
'admin'
>>> ibConst.USER = 'foo' #再代入はエラーになる
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Volumes/Seagate Backup Plus Drive/study/python/infoblox/metaconst.py", line 5, in __setattr__
raise TypeError(f'Can\'t redefine constant ({name})')
TypeError: Can't redefine constant (USER)
>>>
定数クラスをわざわざ作るまでもなく、Enum型で代用することもあるだろう。
>>> from enum import Enum
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.optionxform = lambda option: option
>>> config.read('ibconnect.ini')
['ibconnect.ini']
>>> attr = dict(config.items('gridmaster'))
>>> ibParam = Enum('ibParam', attr) # ConfigParserから得た設定値をEnum型へ代入する
>>> ibParam.GM
<ibParam.GM: '192.168.3.51'>
>>> ibParam.GM.value
'192.168.3.51'
関連ファイル:
まとめ:
INIファイルを読み込んで使うだけならば、即座に実装可能
キーや値のバリデーションは使い回し出来るクラスや関数を準備しておこう
Enum型も便利