从flask中抽离出解析配置文件的模块

从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)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值