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

ponponon發表於2021-11-08
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)

相關文章