-
-
Save marleyiam/68249561d4768bf6ad34c41aa19afb1c to your computer and use it in GitHub Desktop.
Flask application configuration using an environment variable and YAML
This file contains hidden or 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
| os | |
| from flask_extended import Flask | |
| app = Flask(__name__) | |
| app.config.from_yaml(os.join(app.root_path, 'config.yml')) |
This file contains hidden or 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
| COMMON: &common | |
| SECRET_KEY: insecure | |
| DEVELOPMENT: &development | |
| <<: *common | |
| DEBUG: True | |
| STAGING: &staging | |
| <<: *common | |
| SECRET_KEY: sortasecure | |
| PRODUCTION: &production | |
| <<: *common | |
| SECRET_KEY: shouldbereallysecureatsomepoint | |
This file contains hidden or 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 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): | |
| env = os.environ.get('FLASK_ENV', 'development') | |
| self['ENVIRONMENT'] = env.lower() | |
| with open(config_file) as f: | |
| c = yaml.load(f) | |
| c = c.get(env, c) | |
| for key in c.iterkeys(): | |
| if key.isupper(): | |
| self[key] = c[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