How can I override config parameters in Flask config?

感情迁移 提交于 2019-12-30 07:34:27

问题


I am using flask config and I configure my app like so:

app = Flask(__name__)
app.config.from_object('yourapplication.Config')

My Config object is this:

class Config(object):
    DEBUG = True
    TESTING = False
    DB_USER = os.getenv("DB_USER", "db_user")
    DB_PASSWORD = os.getenv("DB_PASSWORD", "db_password")
    DB_HOST = os.getenv("DB_HOST", "localhost")  # 127.0.0.1"
    DB_PORT = os.getenv("DB_PORT", "5555")
    DB_SCHEMA = "my_schema"
    DB_DATABASE_NAME = "my_database"
    SQLALCHEMY_DATABASE_URI = "postgresql://{}:{}@{}:{}/{}".format(
        DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_DATABASE_NAME)
    SQLALCHEMY_TRACK_MODIFICATIONS = False

I run my app like so (using flask-script):

my_flask_app cmd1 arg1 arg2

I would like to do the following:

DEBUG=true DB_PORT=1234 my_flask_app cmd1 arg1 arg2

and override the 2 config parameters. I am wondering if there is already a way to override config parameters from the command line or if I should go and write some code?

EDIT: To clarify, I have several preset configs which inherit from 'Config(object)' like so:

class Dev(Config):
    pass

class Ua(Config):
    pass

class Prod(Config):
    DEBUG = False

My app defaults to 'Dev' config. It is easy to imagine a scenario in which you want to run 'UA' config but override the port like so:

FLASK_ENV=UA DB_PORT=1234 my_flask_app cmd1 arg1 arg2

'FLASK_ENV' will internally select the 'UA' config object but I'd like DB_PORT to be applied on top. Just wondering if there is an extension or someone has had any thoughts on this.


回答1:


There are a few ways for overriding.

1) using config.from_envvar + config.cfg. Example:

# test.py
import json

from flask import Flask, current_app


class Config(object):
    DEBUG = True
    TESTING = False
    DB_PORT = 1234


app = Flask(__name__)
app.config.from_object('test.Config')
app.config.from_envvar('YOURAPPLICATION_SETTINGS', silent=True)


@app.route('/')
def index():
    return json.dumps({
        'DEBUG': current_app.config['DEBUG'],
        'DB_PORT': current_app.config['DB_PORT'],
    })


if __name__ == '__main__':
    app.run()

config.cfg:

DB_PORT = 4321
DEBUG = False

Run our app: python test.py and open http://127.0.0.1:5000/. You will see the default values of config:

{"DEBUG": true, "DB_PORT": 1234}

Now add path of config.cfg into YOURAPPLICATION_SETTINGS variable and restart app.

export YOURAPPLICATION_SETTINGS={full_path_to}/config.cfg
python test.py
# open http://127.0.0.1:5000/ 
# you will see {"DEBUG": false, "DB_PORT": 4321}

2) Similar to the first way, but without .cfg. test.py:

import json
import os

from flask import Flask, current_app


class Config(object):
    DEBUG = True
    TESTING = False
    DB_PORT = 1234


class ProductionConfig(Config):
    DEBUG = False
    DB_PORT = 4321


class TestingConfig(Config):
    TESTING = True


app = Flask(__name__)
app.config.from_object(os.environ.get('CONFIG_CLASS', 'test.Config'))
# route + run ...

How to check:

python test.py # open http://127.0.0.1:5000/ - default config
# ProductionConfig config
export CONFIG_CLASS=test.ProductionConfig
python test.py # open http://127.0.0.1:5000/ - production config

3) In some cases only env variables are sufficient.

But be careful you can have problems with types

import json
import os

from flask import Flask, current_app


class Config(object):
    DEBUG = True
    TESTING = False
    DB_PORT = 1234


app = Flask(__name__)
app.config.from_object('test.Config')
app.config.update({
    'DB_PORT': os.environ.get('DB_PORT', Config.DB_PORT)
    # you should to set type of variable here
    # DB_PORT will be string
    # 'DB_PORT': int(os.environ.get('DB_PORT', Config.DB_PORT))
})
# route + run ...

Let's check:

export DB_PORT=4321
python test.py

Open http://127.0.0.1:5000/ you will see that DB_PORT was changed but is not integer. So this is a good solution for some settings and for specific cases. I think that 1 and 2 ways are better.

Hope this helps.




回答2:


There does not seem to be a standard way of achieving this functionality or a library that adds this useful behaviour at present.



来源:https://stackoverflow.com/questions/50309545/how-can-i-override-config-parameters-in-flask-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!