Updated April 11, 2023
Definition of Flask Environment Variables
Flask environment variables are defined as a set of parameters that facilitates the running of application developed in Flask. An environment for flask applications is essentially a directory or a placeholder that contains all the pre-requisite for successfully running an application. It is assumed to be a surrounding created in order for an application to run. The environment variables come in handy as it allows users to tweak parameters enabling them download tools for building flask application to run, test, and operationalize only for the sake of running the application without hampering the system-wide variables. This also allows users to categorize the type of environment for the flask application, the details of which we will learn in the forthcoming sections!
Syntax
In this section, we will look at the syntax involved in environment variables, so that when we understand the working of environment variables in-depth, the peek-in of syntax will enable us to have a closely relate to the working and will promote quicker understanding.
Configure environment variable one by one:
appConfig = Flask(__name__)
appConfig.config['<config variable>'] = <config variable's value>
Configure environment variable from config.cfg:
In the python code:
appConfig = Flask(__name__)
appConfig.config.from_envvar('APP_SETTINGS')
In command window:
export APP_SETTINGS = <path to the config file>
Setting the FLASK_APP environment variable:
In command window:
export FLASK_APP=<python file name>
Setting the FLASK_ENV environment variable:
In command window:
export FLASK_ENV=<environment name>
How Environment Variables work in Flask?
Before we start learning about environment variables, it is necessary for us to know about the environments which Flask supports. It is the availability of different environments that reason to having multiple configurations because every configuration file is environment-related. The several categories in which the environment is segregated are:
- Development: This environment consists of a set of processes and programming tools that facilitate the developer to build the program or the software product. This environment acts like an experimental playground for the developer so that one can test, debug, experiment, and then finalize on the tools that will go into the final program.
- Testing: This environment relates to the system having configurations built for enabling developers to run test cases enhancing the confidence in the actual product. The development environment might consist of various tools as a result of experimentation, and we don’t know the dependencies, if applicable, on any of the tools. As a result, the testing environment helps create an identical environment every time one needs to test the product so that the integration in the production environment is seamless.
- Production: This environment consists of a set of processes and programming tools that facilitate the end-user for their operations. The software developed in the development environment and after getting tested in the testing environment gets actually put into the production environment for operation of the end-users. This is a real-time setting that has all the required hardware installed and relied on for any commercial purposes.
Now that we have a fair idea of all the environment applicable in the context of Flask, we would now look at what environment variables are and their working. In the introduction session, we have extensively gone through the definition of the environment variables, which we can in short describe as a set of parameters that facilitates the running of application in the prescribed environment we intend the application to run.
While we use these parameters to ease off some repetitive coding for our flask application, we should keep in mind that the usage is totally voluntary and one can easily switch to either of the ways as per the requirement of the application developed. For understanding the working let us take an example through which we can go through step by step. From one of our earlier article of Flask session, we had the following code:
Python code:
from flask import Flask, redirect, url_for, render_template, request, session
from datetime import timedelta
appFlask = Flask(__name__)
appFlask.secret_key = "27eduCBA09"
@appFlask.route("/login")
def login():
session["user"] = "user1"
return '''<h1>The session value is: {}</h1>'''.format(session["user"])
if __name__ == "__main__":
appFlask.run(debug=True)
Command-line:
python <PYTHON FILE NAME>
We see here at the last 2 lines, that the main function consists code that we can easily integrate into one and easily run the application through command line using the FLASK_APP environment variable. The modified code after removing the last 2 lines of the code will look like:
Python code:
from flask import Flask, redirect, url_for, render_template, request, session
from datetime import timedelta
appFlask = Flask(__name__)
appFlask.secret_key = "27eduCBA09"
appFlask.permanent_session_lifetime = timedelta(minutes=5)
@appFlask.route("/login")
def login():
session["user"] = "user1"
return '''<h1>The session value is: {}</h1>'''.format(session["user"])
Command-line:
set FLASK_APP=<PYTHON FILE NAME> flask run
Using the above command-line environment variable, we can run the python code using the single command line and in addition to that, we can reduce 2 extra lines of boilerplate code. One can think of The FLASK_APP variable that it takes into account that one needs to convert the python code into a flask application and then learning from the later part of the command that it should run the flask application. It looks as if the FLASK_APP variable incorporates the 2 lines of code that we avoided.
Similarly, the FLASK_ENV variable sets the environment on which we want our flask application to run. For example, if we put FLASK_ENV=development the environment will be switched to development. By default, the environment is set to development. Now let us look at some example so that one can easily understand “what happens in reality”!
Examples
Let us discuss examples of Flask Environment Variables.
Example #1
Setting the FLASK_APP environment variable
Syntax
Before FLASK_APP variable (The python file name is flaskSession.py):
python flaskSession.py
After FLASK_APP variable (The python file name is flaskSessionAppVariable.py):
set FLASK_APP= flaskSessionAppVariable.py flask run
Output:
Example #2
Set the session to development instead of production:
Syntax
set FLASK_ENV=development
Output
Conclusion
In this article, we have got to know about the details of environment that flask facilitates along with the variables that not only facilitates developers to write smaller and neat codes but also reduce a lot of errors that might creep in due to negligence. Rest is on to the readers to start experimenting with the environment variables in their daily development!
Recommended Articles
This is a guide to Flask Environment Variables. Here we discuss the definition, How Environment Variables work in Flask? examples with code implementation respectively. You may also have a look at the following articles to learn more –