Created
September 20, 2016 14:28
-
-
Save jesseops/f03971f4c94cd9086dac92636982b518 to your computer and use it in GitHub Desktop.
Simple support for YAML configuration in Flask
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 yact | |
from flask import Flask, Config, jsonify | |
# Build custom configuration object | |
class YactConfig(Config): | |
""" | |
Customized config object | |
Extends Flask config to support YAML via YACT | |
""" | |
def from_yaml(self, config_file, directory=None): | |
""" | |
All this method needs to do is load config | |
from our config file, then *add* that config | |
to the existing app config | |
""" | |
config = yact.from_file(config_file, directory=directory) | |
for section in config.sections: | |
# Convention is to use all uppercase keys, we'll just force it | |
self[section.upper()] = config[section] | |
# Override flask's default config class | |
Flask.config_class = YactConfig | |
app = Flask(__name__) | |
app.config.from_yaml('flask-yact.yaml') | |
@app.route('/') | |
def index(): | |
return app.name | |
@app.route('/config') | |
def config(): | |
return jsonify(app.config) | |
if __name__ == "__main__": | |
# Note that we access uppercase 'PORT' | |
app.run('localhost', port=app.config['PORT']) |
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
--- | |
debug: true | |
port: 9000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment