Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn django's settings object into a dict?

What I have:

from django.conf import settings

def settings_to_dict(settings)
    cfg = {
        'BOTO3_ACCESS_KEY': settings.BOTO3_ACCESS_KEY,
        'BOTO3_SECRET_KEY': settings.BOTO3_SECRET_KEY,
        # repeat ad nauseum
    }
    return cfg

instance = SomeClassInstantiatedWithADict(**settings_to_dict(settings))

What I'd like (using Django 1.11):

from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.to_dict())

I've tried:

from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.__dict__)

which is close, but __dict__ only gets a small subset of the settings, which I assume are hard coded ones as opposed to added attributes. Thanks for any help!

like image 480
thclark Avatar asked Dec 05 '17 16:12

thclark


2 Answers

Use the following code:

from django.conf import settings
instance = settings.__dict__['_wrapped'].__dict__

Then you will have the whole settings dict in instance as dictionary.

like image 200
akimul Avatar answered Oct 23 '22 07:10

akimul


Are you sure you really need ALL the settings?

Why not use a little helper, you pass in all the settings u need and a default value. Like this you always get a dict with the settings you actually need, even if they aren't configured.

    def build_settings_dict(attrs=[{'name': 'DEBUG', 'default': False},]):
        settings_dict = {}
        for attr in attrs:
            logger.info(attr)
            try:
                s = getattr(settings, attr['name'], attr['default'])
            except Exception as e:
                logger.warning("Error: %s", e)
            else:
                settings_dict[attr['name']] = s
        return settings_dict


    default_settings = build_settings_dict([
       {'name': 'DEBUG', 'default': True},
       {'name': 'USE_I18N', 'default': True},
       {'name': 'USE_L10N', 'default': False},
    ])
like image 1
dirkbo Avatar answered Oct 23 '22 06:10

dirkbo