Create environment variables in Flask .flaskenv

Video thumbnail

Having learned how to create a CRUD routing system in Flask, another important factor is how to configure environment variables in Flask. This might seem optional, but it's actually a key piece for your application to function correctly, especially when using tools like Flask Migrate, the interactive Shell, or the flask run command.
In my case, it was when integrating Flask Migrate that I understood the importance of having the environment variables well-defined. Without them, Flask didn't even know which application to run.

From the terminal (Windows, Linux, and macOS)

Before using files, you could set them like this:

# In Linux / macOS
export FLASK_APP=my_app
# In Windows
set FLASK_APP=my_app

What are environment variables and why do they matter in Flask

Environment variables are values external to the code that define an application's behavior. In Flask, they are used, for example, to indicate which application should be started, the execution mode, or the server port.

What role they play in development and security

Their function is to separate sensitive configuration from the source code. This way, you avoid exposing keys or tokens (e.g., SECRET_KEY or API_KEY) in the project files.

Difference between global and application variables

Global ones affect the operating system (e.g., PATH), while application ones control Flask's behavior (FLASK_APP, FLASK_ENV, FLASK_DEBUG, etc.).
Thanks to this, you can maintain different environments: development, testing, and production, without modifying your base code.

.env and .flaskenv files: The modern way to configure Flask

When I started working with Flask, I had to set the variables manually every time I opened a terminal. Then I discovered that Flask allows managing them from files.

This greatly facilitates the workflow, as it's enough to create two files in the project root: .env and .flaskenv.

What is the difference between .env and .flaskenv

File    Purpose    Example
.flaskenv    Configuration for Flask CLI commands    FLASK_APP=my_app
.env    General application configuration

We saw how to set it via the terminal as shown in chapter 5, where it was required to run Flask Migrate commands. But we haven't seen all the potential this offers us and how Flask uses it. For example, we can use files to handle these environment variables, just like with technologies like CodeIgniter or Laravel, we can create these files to manage the project's environment variables:

Where they are created and how Flask detects them

Both are placed in the project root folder. Flask detects them automatically if you have the python-dotenv package installed.

Practical example of project structure
my_app/

├── __init__.py
├── config.py
├── .env
├── .flaskenv
└── run.py

.env

And in the case of Flask, also the:

.flaskenv 

To manage these environment variables.

In this chapter, we will learn how to use environment variables through files.

We are going to create a new application as discussed in chapter 1.

If we try to execute:

$ flask run

We will see an error like the following:

Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.

Which indicates that the environment variable called FLASK_APP must be set, indicating the name of the application module in Flask.

To do this, we can do it via the terminal, on Mac or Linux:

$ export FLASK_APP=my_app

On Windows:

$ set FLASK_APP=my_app

Or set it in the file:

.flaskenv

FLASK_APP=my_app

The value of FLASK_APP corresponds to the module name, which in this example is called my_app:

my_app/__init__.py

config.py

.env

.flaskenv

run.py

Where the application startup file is located:

my_app/__init__.py

Now, if we try to execute the command:

$ flask run

We will see that it still doesn't work; this is because Flask is not recognizing the previously generated file; for it to recognize it as a valid entry for setting environment variables, we must install an additional package:

$ pip install python-dotenv

If we execute again:

$ flask run

We will see that the server now starts correctly; if we try to execute other commands that require knowing the application instance, the variable called app which is inside my_app/__init__.py.

The fundamental advantage of using files to manage environment variables is that we don't have to set the environment variables for our application every time we open a terminal, as they are taken from the file.

These are the main options we can configure:

  • FLASK_ENV - Indicates the environment, by default it is production.
  • FLASK_DEBUG - Indicates if the application is in DEBUG mode, by default it is TRUE.
  • FLASK_APP - Used to specify the application module.
  • FLASK_RUN_PORT - To specify the port when starting the application.

You can find other Flask environment variables at:

https://flask.palletsprojects.com/en/latest/config/

We have two dot files: .env and .flaskenv. We use .flaskenv for any Flask CLI configuration command and use .env for our application configuration.

For example, we specify the module name, as we did before:

.flaskenv

FLASK_APP=my_app

And in this file any other configuration that does not have the FLASK_* prefix:

.env

SECRET_KEY=12345 
API_KEY=123

We can specify other configurations such as:

.flaskenv

FLASK_ENV=development 
FLASK_RUN_PORT=8080

To access environment variables from the project, we must use the environ() function:

config.py

from os import environ 
SECRET_KEY = environ.get('SECRET_KEY')
API_KEY = environ.get('API_KEY')
FLASK_APP = environ.get('FLASK_APP')

The main advantage of using files to manage environment variables is that we can have all the project's environment variables in one place, we can have multiple configurations in other .env type files and switch between them easily, and have files to manage the environment variables for development, production, testing, among others.

Best practices and multiple environments (dev, test, prod)

In real projects, I usually have several .env files: one for development, another for production, and another for testing.
This avoids mixing configurations and facilitates continuous deployment.

Separate configurations without getting complicated

Create copies of the .env file:

.env.development .env.production .env.test

And switch between them according to the environment you need.

Example of use with multiple .env files

You can write a small script to load the appropriate file before starting Flask.

Tips for maintaining security

  • Do not upload .env files to your repository (use .gitignore).
  • Avoid including sensitive keys in plain text.

❌ Common errors and how to solve them


“Could not locate a Flask application…”

Occurs when FLASK_APP does not point to the correct module. Check the file name or the content of .flaskenv.

Unrecognized or duplicated variables

Make sure python-dotenv is installed and that you don't have unnecessary spaces or quotes in the .env files.

When Flask ignores the .flaskenv file

If you run your application from a virtual environment or external server without python-dotenv, Flask will not automatically read the environment files. Load them manually in __init__.py.

Main environment variables that we can use in Flask

In Flask we have multiple environment variables that we can use to perform different configurations, activate debug mode, specify the startup or main file of the application, among many other configurations that we can perform.

In this post we are going to see some of the main environment variables that we can use in Flask.

Environment variable: FLASK_APP

This has been if it is not the most important, one of the most important that we must know; with this we are indicating which is the startup file of our project in Flask; Its use is very simple:

Example of its use: (Linux and MacOS)

export FLASK_APP=run.py

With this configuration we can indicate the startup file of our application. So when we go to run the app with:

Flask run

Flask is going to take the configuration of the name that we configured before to run the app

We can also execute other types of configurations, for example, when we execute a migration with Flask Migrate, as we dealt with in the course of:

And well, there are many processes or packages that you can install in which you must specify the FLASK_APP before starting said process, since with this, we are indicating where all the dependencies and our project as such begin to be loaded.

Environment variable: FLASK_DEBUG

With this configuration we can enable or disable the debut mode in our application that serves us, for example, to show detailed information about an error that is occurring in our app and is also used by other packages, for example, Flask Google Captcha to enable the use of the captcha or disable it.

Example of its use: (Linux and MacOS)

export FLASK_DEBUG=1

Environment variable: FLASK_ENV

With this we can configure the environment of our application

Example of its use: (Windows)

set FLASK_ENV=development

You can see the full list of Flask environment variables in Environment Variables

Conclusion

Using environment variables correctly makes the difference between an amateur project and a professional one. This way, we can easily reuse key pieces of code. Configuring .env and .flaskenv saved me time, errors, and allowed me to automate deployments without touching the code.

❓ Frequently asked questions

Why use .flaskenv if I already have .env?
Because .flaskenv is read first and allows Flask CLI to know the module and environment without being executed manually.

What happens if I don't install python-dotenv?
Flask will not automatically load the .env or .flaskenv files, and you will have to export the variables every time.

Can I define different variables depending on the environment?
Yes, you can have multiple .env files (e.g., .env.dev, .env.prod) and load them according to the project phase.

The next step is to learn how to work with Jinja2 for template management

I agree to receive announcements of interest about this Blog.

Environment variables are an important part of the application since in order to use certain tools such as Flask Migrate, the Shell or the Flask run command, we must establish the environment variable called FLASK_APP.

| 👤 Andrés Cruz

🇪🇸 En español