从flask中抽离出来的解读如下形式配置文件的模块:
【配置文件】
#main.conf
USERNAME=xx
PASSWORD=xx
PYTHON=xxxx
【使用介绍】
cfg = config.Config()
cfg.load_config('main.conf')
cfg.get('USERNAME','work')
cfg.get('PASSWORD','xxx')
【源代码】
import os
import sys
import imp
class Config(dict):
"""Works exactly like a dict but provides ways to fill it from files.
"""
def __init__(self,defaults=None):
dict.__init__(self, defaults or {})
@classmethod
def instance(cls,conf_name="main.conf"):
"""load config file"""
key = "_{0}".format(conf_name)
if hasattr(cls,key):
return getattr(cls,key)
else:
d = imp.new_module('config')
d.__file__ = conf_name
with open(conf_name) as config:
exec(compile(config.read(),conf_name,'exec'),d.__dict__)
cfg = Config()
cfg.from_object(d)
setattr(cls,key,cfg)
return getattr(cls,key)
def from_object(self, obj):
"""Updates the values from the given object. An object can be of one
of the following two types:
- a string: in this case the object with that name will be imported
- an actual object reference: that object is used directly
Objects are usually either modules or classes.
:param obj: an import name or object
"""
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key)