Organising Flask Configurations

The beginner’s method

from flask import Flaskapp = Flask(__name__)app.config['APP_ROOT'] = os.path.dirname(os.path.abspath(__file__))
app.config['MONGO_URI'] = "mongo_uri"
app.config['SECRET_KEY'] = "secret_key"
@app.route("/")
def index():
return "Welcome Home!", 200
if __name__ == "__main__":
app.run()

Pros

  1. This method is a very quick way of configuring our applications and while keeping all the code in one file.
  2. Keeps our application simple if we plan on running it in only one environment (which is extremely rare for non-experimental projects as we would need at least development & production environments).

Cons

  1. If you have many app configuration values, the file can quickly become too long.
  2. If you have multiple environments, you will have to manually adjust the app configurations for each environment with every release. This can become a nightmare very quickly.
  3. In addition to the former point, you’re more prone to make mistakes while updating app configuration values between environments
  4. If there are any configurations that you want to keep secret (from a public repository for example), you will have a difficult time doing that with this method (although you could use environment variables, but that’s a topic for another article).

Better methods

1. Configuration files

MONGO_URI = "environment_mongo_uri"
SECRET_KEY = "environment_secret_key"
app.config.from_pyfile('production.cfg')
app.config.from_pyfile('development.cfg')
app.config.from_pyfile('production.cfg')
try:
app.config.from_pyfile('development.cfg')
except FileNotFoundError:
pass

2. Configuration objects

class BaseConfig(object):
DEBUG = False
MONGO_URI = "mongo_uri"
class DevelopmentConfig(BaseConfig):
DEBUG = True
MONGO_URI = "development_mongo_uri"
class TestingConfig(BaseConfig):
DEBUG = True
MONGO_URI = "testing_mongo_uri"
class ProductionConfig(BaseConfig):
MONGO_URI = "production_mongo_uri"
app.config.from_object('configmodule.ProductionConfig')

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store