Dave Cinege Git Repo thesaurus / master thesauruscfg_sample.py
master

Tree @master (Download .tar.gz)

thesauruscfg_sample.py @masterraw · history · blame

###
# Python Thesaurus Config Sample
#
# Copyright (c) 2019 Dave Cinege
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
from __future__ import print_function

__VERSION__ = (2, 9, 0, 20200108)

import os
import sys
import json

from thesauruscfg import thescfg

def main ():
	cfg = thescfg()
	cfg.read('thesauruscfg_sample.cfg')

	print('cfg.print_tree()\n---')
	cfg.print_tree()
	print('---')

	# mesh in the default.gateways values (don't overwrite existing)
	# FIX ME not yet copying the coercion methods
	for k,t in cfg.networks.items():
		print('mesh: cfg.networks.{0}.gateways'.format(k))
		t.gateways.mesh(cfg.defaults.gateways)
	print('---\n')

	print('cfg.dump()\n---')
	print(cfg.dump())
	print('---')

	# thesauruscfg is perfect for JSON
	print('json.dumps()\n---')
	js = json.dumps(cfg, indent=4, separators=(',', ': '))
	print(js)
	print('---')

	print('cfg_json = json.loads(), cfg_json.print_tree()\n---')
	cfg_json = json.loads(js, object_hook=thescfg)
	cfg_json.print_tree()
	print('---')

	# abc is using the static_int() coercion method. The method not only
	# converts to and from an int, it will not allow further value assignment
	# keeping it static.
	oldabc = cfg.abc
	cfg.abc = 0
	cfg['abc'] = 'even the wrong type'
	if oldabc == cfg.abc:
		print('abc: static value will not change.')
	else:
		print('abc: is broken!')

	cfg.a.bc = 'aaa'
	if cfg.a.bc == 456:
		print('a.bc: static value = 456 will not change.')
	else:
		print('a.bc: is broken!')


	try:
		cfg.defaults.gateways.router = '1.1.1.666'
	except ValueError:
		print('cfg.defaults.gateways.router: That was a bad ipv4.')
	else:
		print('cfg.defaults.gateways.router: ok ipv4.')
	

if __name__ == '__main__':
	main()