因为业务需要,我需要创建一个可以在多模块公用全局变量,根据https://www.jianshu.com/p/6cee728f3490的代码,因为他提供的只能生成 { k: v, kk: v ... } 的数据格式
我需要构建二维的全局变量格式,是 { { k: v }, { k: v} ... } 的结构,就对代码进行了一些改动,供大家学习参考
class GlobalMap:
# 拼装成字典构造全局变量 借鉴map 包含变量的增删改查
map = {"default": {}}
def set_map(self, key, value, group="default"):
if isinstance(value, dict):
value = json.dumps(value)
if group in self.map: # 判断key是否存在
if key in self.map[group]:
self.map[group][key] = value
else:
self.map[group].setdefault(key, value)
else:
self.map.setdefault(group, {key: value})
def set(self, group="default", **keys):
try:
for key_, value_ in keys.items():
self.map[group][key_] = str(value_)
log.debug(key_ + ":" + str(value_))
except BaseException as msg:
log.error(msg)
raise msg
def del_map(self, key, group="default"):
try:
del self.map[group][key]
return self.map
except KeyError:
log.error(f" '{group}' 或 key:'{str(key)}' 不存在")
def get(self, *args, group="default"):
try:
dic = {group: {}}
for key in args:
if args[0] == 'all' and len(args) == 1:
dic[group] = self.map[group]
elif len(args) == 1:
dic[group] = self.map[group][key]
log.debug(group + "->" + key + ":" + str(dic))
else:
dic[group][key] = self.map[group][key]
return dic[group]
except KeyError:
log.error(f" '{group}' 或 key:'{str(key)}' 不存在")
return 'Null_'
测试代码
a = GlobalMap() a.set_map("aa", "66", group="demo") a.set_map("bb", "77", group="demo") a.set_map("cc", "88", group="demo") print(a.map) c = a.get("aa", "bb", group="demo") print(c)
输出结果
1. {'default': {}, 'demo': {'aa': '66', 'bb': '77', 'cc': '88'}} 2. {'aa': '66', 'bb': '77'}
input
1. c = a.get("aa", group="demo")
output
1. 66
input
c = a.get("all", group="demo")
output
{'aa': '66', 'bb': '77', 'cc': '88'}