Skip to content

Instantly share code, notes, and snippets.

@mattdeboard
Last active July 16, 2016 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattdeboard/3cbe5395052128e60328 to your computer and use it in GitHub Desktop.
Save mattdeboard/3cbe5395052128e60328 to your computer and use it in GitHub Desktop.
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)
@maxcountryman
Copy link

Hi I read your comment on HN: I would recommend using a function to configure you app object with. This would allow you to inject and overload the configuration process with deployment-specific environment variables. Maybe something along these lines:

import os

from flask import Flask

# ...


def setup_app():
    app = Flask(__name__)
    app.config.from_object('myapp.config')

    if 'MYAPP_CONFIG' in os.environ:
        app.config.from_envvar('MYAPP_CONFIG')

   # do some other things...

    return app

@mattdeboard
Copy link
Author

What does that get me that my original solution doesn't?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment