Skip to content
Advertisement

Configure Python Flask RESTplus app via TOML file

Based on the Configuration Handling Documents for Flask the section of Configuring from Files mentions a possibility to configure the App using files however it provides no example or mention of files that are not Python Files.

Is it possible to configure apps via files like config.yml or config.toml?

My Current flask app has configurations for two distinct databases and since I am using flask-restplus there are additional configurations for Swagger documentations.

Snippet:

from flask import Flask

app = Flask(__name__)

def configure_app(flask_app):

    # MongoDB Setting
    flask_app.config['MONGO_URI'] = 'mongodb://user:password@mongo_db_endpoint:37018/myDB?authSource=admin'
    flask_app.config['MONGO_DBNAME'] = 'myDB'

    # InfluxDB Setting
    flask_app.config['INFLUXDB_HOST'] = 'my_influxdb_endpoint'
    flask_app.config['INFLUXDB_PORT'] = 8086
    flask_app.config['INFLUXDB_USER'] = 'influx_user'
    flask_app.config['INFLUXDB_PASSWORD'] = 'influx_password'
    flask_app.config['INFLUXDB_SSL'] =  True
    flask_app.config['INFLUXDB_VERIFY_SSL'] = False
    flask_app.config['INFLUXDB_DATABASE'] = 'IoTData'

    # Flask-Restplus Swagger Configuration
    flask_app.config['RESTPLUS_SWAGGER_UI_DOC_EXPANSION'] = 'list'
    flask_app.config['RESTPLUS_VALIDATE'] = True
    flask_app.config['RESTPLUS_MASK_SWAGGER'] = False
    flask_app.config['ERROR_404_HELP'] = False

def main():
    configure_app(app)

if __name__ == "__main__":

    main()

I would like to avoid setting large number of Environment Variables and wish to configure them using a config.toml file?

How is this achieved in flask?

Advertisement

Answer

You can use the .cfg files and from_envvar to achieve this. Create config file with all your environment variables.

my_config.cfg

MONGO_URI=mongodb://user:password@mongo_db_endpoint:37018
..
..
ERROR_404_HELP=False

Then set the env var APP_ENVS=my_config.cfg. Now all you need to do is use from_envvars given by Flask.

def configure_app(flask_app):
    flask_app.config.from_envvar('APP_ENVS')
    # configure any other things
    # register blue prints if you have any
Advertisement