What's a djangonautic way of handling default settings in an app if one isn't defined in settings.py
?
I've currently placed a default_settings
file in the app and I've considered a few options. I'm leaning towards the first option, but there may be pitfalls I'm not aware of in using globals()
I've mostly seen apps do a FOO = getattr(settings, 'FOO', False)
at the top of the file that uses the setting but I think there are readability/repetition problems with this approach if the values / names are long.
1: Place settings in a function and iterate over locals / set globals
def setup_defaults():
FOO = 'bar'
for key, value in locals().items():
globals()[key] = getattr(settings, key, value)
setup_defaults()
Pros:
- Only have to write var name once to pull default of same name from django settings.
Cons:
- Not used to using globals() and don't know of any implications
2: Write getattr(settings, 'MY_SETTING', default_settings.MY_SETTING)
every call
Pros:
- Very clear.
Cons: - Repetitive
3: Always define settings as FOO = getattr(settings, 'FOO', '...setting here...')
Pros:
- Defaults are always overridden
Cons:
- Repetitive (must define var twice - once in string form, once in var)
- Setting is not as readable since it's now the third argument
4: Create utility function to get_or_default(setting)
Pros:
- Simple
- Don't have to repeat string representation of setting
Cons:
5: Create a settings class
class Settings(object):
FOO = 'bar'
def __init__(self):
# filter out the startswith('__') of
# self.__dict__.items() / compare to django.conf.settings?
my_settings = Settings()
Cons:
- Can't do from foo.bar.my_settings import FOO (actually, that's a terrible deal breaker!)
I'd love to hear feedback.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…