Flask Configuration
Configuration
We run basic flask app in How to create a website with Python Flask and we set ENV config value (environment) to development. In flask, we can set different values (setting) base on environment (ENV). Default ENV is production. Later we will need to set debug mode, secret key , database url and add other new values to flask. Then we deploy to server, we need to set ENV to production and change the values again. So we need to prepare to change the values base on application environment.
Print all config values in your flask app
from flask import Flaskapp = Flask(__name__)
print(app.config)@app.route("/")
def home():
return "This is Home Page"if __name__ == "__main__":
app.run(debug=True)
Add new config value
ap.config['SECRET'] = "secret"
print(app.config)
ENV config
Production
ENV config value is which environment you app is running. Default ENV is production. Run production server when deploy
app.config['ENV'] = 'production'
Development
development mode reload the code when it is changed.
When you run flask you will see above warning. Then set below code
app.config['ENV'] = 'development'
Set configuration values depend on application environment
- create config.py
class Config(object):
DEBUG = False
TESTING = Falseclass ProductionConfig(Config):
ENV = 'production'class DevelopmentConfig(Config):
ENV = 'development'
DEBUG = True
means that in production server ENV is production. In development server ENV is development and debug mode is true.
You can set more config values.
- in main.py
from flask import Flaskapp = Flask(__name__)
app.config.from_object("config.DevelopmentConfig")@app.route('/')
def home():
return "home"if __name__ == "__main__":
app.run()