django 自定义配置报错: AttributeError: 'Settings' object has no attribute 'HBase'

如果我们需要用到 Hbase 的话,可以仿照 Mysql 一样,把相关的信息配置写入到 settings 文件中,但是我遇到了一个问题,就是无法导入。

In [12]: settings.HBASE
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-22bd47148938> in <module>
----> 1 settings.HBASE

~\.virtualenvs\twitter-5Z0qCgub\lib\site-packages\django\conf\__init__.py in __getattr__(self, name)
     81         if self._wrapped is empty:
     82             self._setup(name)
---> 83         val = getattr(self._wrapped, name)
     84
     85         # Special case some settings which require further modification.

AttributeError: 'Settings' object has no attribute 'HBASE'

In [13]: settings.HBase
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-1ee0306304e8> in <module>
----> 1 settings.HBase

~\.virtualenvs\twitter-5Z0qCgub\lib\site-packages\django\conf\__init__.py in __getattr__(self, name)
     81         if self._wrapped is empty:
     82             self._setup(name)
---> 83         val = getattr(self._wrapped, name)
     84
     85         # Special case some settings which require further modification.

AttributeError: 'Settings' object has no attribute 'HBase'

结果问题的排查发现,在 Django 的配置文件 settings 中,必须使用全部大小才能被导入。

HBase --> HBASE

HBase = {
    'default': {
        'HOST': '192.168.31.245',
        'PORT': 9090
    }
}

需要改为

HBASE = {
    'default': {
        'HOST': '192.168.31.245',
        'PORT': 9090
    }
}
大小写错误! 不要在 Django 的配置文件 settings 中混合使用大小写,必须全部是大写!

从下面的文件中可以看到关键代码 if setting.isupper():

django/conf/__init__.py

class Settings:
    def __init__(self, settings_module):
        # update this dict from global settings (but only for ALL_CAPS settings)
        for setting in dir(global_settings):
            if setting.isupper():
                setattr(self, setting, getattr(global_settings, setting))

        # store the settings module in case someone later cares
        self.SETTINGS_MODULE = settings_module

        mod = importlib.import_module(self.SETTINGS_MODULE)

        tuple_settings = (
            "INSTALLED_APPS",
            "TEMPLATE_DIRS",
            "LOCALE_PATHS",
        )
        self._explicit_settings = set()
        for setting in dir(mod):
            if setting.isupper():
                setting_value = getattr(mod, setting)

                if (setting in tuple_settings and
                        not isinstance(setting_value, (list, tuple))):
                    raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting)
                setattr(self, setting, setting_value)
                self._explicit_settings.add(setting)

universe_king
3.4k 声望680 粉丝