Skip to content

Instantly share code, notes, and snippets.

@apavamontri
Forked from mattupstate/app.py
Last active December 12, 2015 08:59
Show Gist options
  • Save apavamontri/4748579 to your computer and use it in GitHub Desktop.
Save apavamontri/4748579 to your computer and use it in GitHub Desktop.
os
from flask_extended import Flask
app = Flask(__name__)
app.config.from_yaml(os.join(app.root_path, 'config.yml'))
COMMON: &common
SECRET_KEY: insecure
DEVELOPMENT: &development
<<: *common
DEBUG: True
STAGING: &staging
<<: *common
SECRET_KEY: sortasecure
PRODUCTION: &production
<<: *common
SECRET_KEY: shouldbereallysecureatsomepoint
"""
You need to install PyYAML library
using pip:
pip install PyYAML
"""
import os
import yaml
from flask import Flask as BaseFlask, Config as BaseConfig
class Config(BaseConfig):
"""Flask config enhanced with a `from_yaml` method."""
def from_yaml(self, config_file):
"""
To make this work in HEROKU, you must set the configuration variable
called "FLASK_ENV".
Type:
heroku config:set FLASK_ENV=production
Verified type:
heroku config
You should see it listed.
FLASK_ENV: production
GEM_PATH: vendor/bundle/ruby/1.9.1
LANG: en_US.UTF-8
PATH: bin:vendor/bundle/ruby/1.9.1/bin:/usr/local/bin:/usr/bin:/bin
RACK_ENV: production
RAILS_ENV: production
"""
# Read 'FLASK_ENV' config value, if it does not exists set 'development'
# as default
env = os.environ.get('FLASK_ENV', 'development')
# Add 'ENVIRONMENT' variable as a reference
self['ENVIRONMENT'] = env.lower()
# Load everything from the YAML file
with open(config_file) as yaml_file:
config_values = yaml.load(yaml_file)
# Get all the variables from the proper 'section' in the YAML.
# The section we are getting is defined by 'FLASK_ENV' value.
# e.g
#
# DEVELOPMENT:
# DEBUG: True
# FB_KEY: ABCDEF
config_values = config_values.get(env.upper(), config_values)
# Assign values to FLASK's app.config
for key in config_values.iterkeys():
# We look at key with uppercase only
if key.isupper():
self[key] = config_values[key]
class Flask(BaseFlask):
"""Extended version of `Flask` that implements custom config class"""
def make_config(self, instance_relative=False):
root_path = self.root_path
if instance_relative:
root_path = self.instance_path
return Config(root_path, self.default_config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment