python实现全局配置和用户配置文件

一、文件目录格式

二、代码

1.conf.__init__.py

import importlib
import os

from conf import gsettings

class Settings(object):
    def __init__(self):
        #先加载全局配置
        for item in dir(gsettings):
            if item.isupper():
                k=item
                v=getattr(gsettings,k)
                #给对象设置键值对
                setattr(self,k,v)
        #加载用户settings
        setting_path=os.environ.get("SETTING")
        settings_module=importlib.import_module(setting_path)
        for s in dir(settings_module):
            if s.isupper():
                k=s
                v=getattr(settings_module,k)
                #给对象设置键值对
                setattr(self,k,v)


settings=Settings()

2.gsettings.py

NAME='from system settings'

3.settings.py

NAME="from customer settings"

4.start.py

import os,sys
BASE_DIR=os.path.dirname(__file__)
sys.path.append(BASE_DIR)

# 设置一个全局的键值对
os.environ.setdefault('SETTING','lib.settings')
from  conf import settings
print(settings.NAME)

 

posted @ 2019-08-29 16:25  Maple_feng  阅读(1769)  评论(0编辑  收藏  举报