From 2fc11edf861135237317b13a7f1eff0ca872d5bd Mon Sep 17 00:00:00 2001 From: Douglas Thor Date: Fri, 6 Jul 2018 13:17:08 -0700 Subject: [PATCH] Provide note about instantiating the config object and example on using @property in config classes --- docs/config.rst | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/docs/config.rst b/docs/config.rst index c2958bf7..d9ff4827 100644 --- a/docs/config.rst +++ b/docs/config.rst @@ -553,6 +553,44 @@ To enable such a config you just have to call into app.config.from_object('configmodule.ProductionConfig') +Note that :meth:`~flask.Config.from_object` does not instantiate the class +object. If you need to instantiate the class, such as to access a property, +then you must do so before calling :meth:`~flask.Config.from_object`:: + + from configmodule import ProductionConfig + app.config.from_object(ProductionConfig()) + + # Alternatively, import via string: + from werkzeug.utils import import_string + cfg = import_string('configmodule.ProductionConfig')() + app.config.from_object(cfg) + +Instantiating the configutation object allows you to use ``@property`` in +your configuration classes:: + + class Config(object): + """Base config, uses staging database server.""" + DEBUG = False + TESTING = False + DB_SERVER = '192.168.1.56' + + @property + def DATABASE_URI(self): # Note: all caps + return 'mysql://user@{}/foo'.format(self.DB_SERVER) + + class ProductionConfig(Config): + """Uses production database server.""" + DB_SERVER = '192.168.19.32' + + class DevelopmentConfig(Config): + DB_SERVER = 'localhost' + DEBUG = True + + class TestingConfig(Config): + DB_SERVER = 'localhost' + DEBUG = True + DATABASE_URI = 'sqlite:///:memory:' + There are many different ways and it's up to you how you want to manage your configuration files. However here a list of good recommendations: