在django项目中手动模拟实现settings的配置

一  文件结构目录

手写配置文件
  有两套配置文件,默认配置,用户的配置
  如果某个字段,用户配置了,就用用户的,如果没配置,就用默认的

1.1  test

import os

os.environ.setdefault('user_setting', 'usersetting.setting')
from conf import settings

print(settings.DEBUG)

1.2  conf 下的 __init__

import os
import importlib
from conf import globalsetting


class Setting:
    def __init__(self):
        user_setting = os.environ.get('user_setting')
        print(dir(globalsetting))
        for setting in dir(globalsetting):
            if setting.isupper():
                setattr(self, setting, getattr(globalsetting, setting))

        mod = importlib.import_module(user_setting)
        print(mod)
        for setting in dir(mod):
            if setting.isupper():
                setattr(self, setting, getattr(mod, setting))


settings = Setting()

1.3  conf 下

globalsetting中:  DEBUG = False

1.4  usersetting下

setting 中:  DEBUG = True

二  运行test

结果为True,则运行的为user的setting

 

posted @ 2018-12-18 16:49  zhaijihai  阅读(320)  评论(0编辑  收藏  举报