Source settings

Custom settings configuration

Create a python project

settings.py

NAME = 'I was exposed to a custom user configuration'

__init__.py

import os
import importlib

from lib.conf import global_settings


class Settings(object):
    def __init__(self):
        #先for循环获取全局配置文件中所有 的变量名
        for name in dir(global_settings):
            #判断是否是大写
            if name.isupper():
                setattr(self,name,getattr(global_settings,name))
        #从全局的大字典中先拿到暴露给用户的配置文件,字符串路径
        path = os.environ.get('xxx') #path = 'conf.settings'
        #利用importlib模块导入settings模块
        module = importlib.import_module(path)
        '''
        
        from conf import settings
        module就是settings模块名
        '''

        #再for循环暴露给用户的文件中所有的变量名
        for name in dir(module):
            if name.isupper():
                k = name
                v = getattr(module,name)
                setattr(self,k,v)

settings = Settings()

global_settings.py

NAME = '我是项目默认的配置'

start.py

import os
import sys

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



if __name__ == '__main__':

    #在项目的全局设置一个大字典
    os.environ.setdefault('xxx','conf.settings')


    from lib.conf import settings
    print(settings.NAME)

  

  

Guess you like

Origin www.cnblogs.com/huangxuanya/p/11544586.html