apppublic/appPublic/jsonConfig.py

75 lines
1.6 KiB
Python
Raw Normal View History

2019-07-16 16:33:07 +08:00
import os,sys
import json
2022-03-13 13:21:01 +08:00
from pathlib import Path
2019-07-16 16:33:07 +08:00
from appPublic.dictObject import DictObject
from appPublic.Singleton import SingletonDecorator
from appPublic.folderUtils import ProgramPath
from appPublic.argsConvert import ArgsConvert
def key2ansi(dict):
#print dict
return dict
a = {}
for k,v in dict.items():
k = k.encode('utf-8')
#if type(v) == type(u" "):
# v = v.encode('utf-8')
a[k] = v
return a
class JsonObject(DictObject):
"""
JsonObject class load json from a json file
"""
def __init__(self,jsonholder,keytype='ansi',NS=None):
jhtype = type(jsonholder)
if jhtype == type("") or jhtype == type(u''):
f = open(jsonholder,'r')
else:
f = jsonholder
try:
a = json.load(f)
except Exception as e:
print("exception:",self.__jsonholder__,e)
raise e
finally:
if type(jsonholder) == type(""):
f.close()
2020-06-07 21:40:44 +08:00
if NS is not None:
2019-07-16 16:33:07 +08:00
ac = ArgsConvert('$[',']$')
2020-06-07 21:42:45 +08:00
a = ac.convert(a,NS)
2020-06-07 21:40:44 +08:00
a['__jsonholder__'] = jsonholder
a['NS'] = NS
2020-06-07 21:43:48 +08:00
DictObject.__init__(self,**a)
2019-07-16 16:33:07 +08:00
@SingletonDecorator
class JsonConfig(JsonObject):
pass
2022-03-13 13:21:01 +08:00
2019-07-16 16:33:07 +08:00
def getConfig(path=None,NS=None):
2022-03-13 13:21:01 +08:00
pp = ProgramPath()
2019-07-16 16:33:07 +08:00
if path==None:
2022-03-13 13:21:01 +08:00
path = pp
2019-07-16 16:33:07 +08:00
cfname = os.path.abspath(os.path.join(path,"conf","config.json"))
# print __name__,cfname
2022-03-13 13:21:01 +08:00
ns = {
'home':str(Path.home()),
'workdir':path,
'ProgramPath':pp
}
if NS is not None:
ns.update(NS)
a = JsonConfig(cfname,NS=ns)
2019-07-16 16:33:07 +08:00
return a
if __name__ == '__main__':
conf = JsonConfig(sys.argv[1])
#print conf.db,conf.sql
#conf1 = JsonConfig(sys.argv[1],keytype='unicode')
conf1 = JsonConfig(sys.argv[1],keytype='ansi')
print("conf=",dir(conf))
print("conf1=",dir(conf1) )