简体   繁体   中英

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 ?

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

Quoting from documentation :

Configuring from Data Files

It is also possible to load configuration from a file in a format of your choice using from_file() . For example to load from a TOML file:

 import toml app.config.from_file("config.toml", load=toml.load)

Or from a JSON file:

 import json app.config.from_file("config.json", load=json.load)

EDIT: The above feature is new for v2.0.

Link to the documentation reference:

Class Flask.config , method from_file(filename, load, silent=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM