-
-
Save mattdeboard/3cbe5395052128e60328 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import importlib | |
import os | |
import sys | |
from flask import Flask | |
__all__ = ['app', 'settings'] | |
class Settings(object): | |
"""A class to allow dynamically generating & encapsulating app | |
settings. When the module is imported, this object looks for an | |
environment variable called "SETTINGS_MODULE". If it doesn't find it, | |
it will default to using settings_module.vagrant. | |
""" | |
def __init__(self): | |
_settings = os.environ.get('SETTINGS_MODULE', | |
'myproject.settings_modules.vagrant') | |
self._settings = importlib.import_module(_settings) | |
for attr, val in self._settings.__dict__.items(): | |
setattr(self, attr, val) | |
def __getattr__(self, name, default=None): | |
attr = getattr(self._settings, name, default) | |
if attr is None and default is None: | |
raise ImportError("Module '%s' has no attribute %s." % | |
(self._settings.__name__, name)) | |
return attr | |
def db_uri(self, db='myproject'): | |
kwargs = self.DATABASES[db] | |
return '{SCHEME}{USER}:{PASSWORD}@{HOST}/{NAME}'.format(**kwargs) | |
settings = Settings() | |
sys.modules['myproject.settings'] = settings | |
app = Flask('myproject') | |
app.config.from_object(settings) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What does that get me that my original solution doesn't?