EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Flask Tutorial Flask Environment Variables
Secondary Sidebar
Flask Tutorial
  • Flask
    • Flask Version
    • Flask make_response
    • Flask WebSocket
    • Flask Session
    • Flask Environment Variables
    • Flask Cache
    • Flask Server
    • Flask jsonify
    • Flask logging
    • Flask redirect
    • Flask wtforms
    • Flask config
    • Flask Users
    • Flask upload file
    • Flask? get post data
    • Flask Template
    • Flask DB Migrate
    • Flask HTTPS
    • Flask bcrypt
    • Flask debug mode
    • Flask authentication
    • Flask Migrate
    • Flask URL Parameters
    • Flask API
    • Flask bootstrap
    • Flask POST request
    • Flask Extensions

Flask Environment Variables

By Alokananda GhoshalAlokananda Ghoshal

Flask Environment Variables

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

appConfig = Flask(__name__)
appConfig.config['<config variable>'] = <config variable’s value>

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,502 ratings)

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:

Flask Environment Variables 1

Flask Environment Variables 2

Example #2

 Set the session to development instead of production:

Syntax:

set FLASK_ENV=development

Output:

Flask Environment Variables 3

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 –

  1. Django vs Flask
  2. Bash Set Variables
  3. Kubernetes Environment Variables
  4. PowerShell Environment Variables
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more