DEV Community

loading...
Cover image for Flask and .env

Flask and .env

Sasidharan
Technophile 🧑🏻‍💻 Creator - lagandlog.com
・1 min read

To learn how to dockerize react application visit - https://lagandlog.com/logs/how-to-dockerize-react-app

env files allow you to put your environment variables inside a file. It actually looks like,

REDIS_ADDRESS=localhost:6379
MEANING_OF_LIFE=42
MY_SECRET="helloworld"
Enter fullscreen mode Exit fullscreen mode

Creating .env files in your projects help you to manage all secrets or variable in a file and in a secret place. It's not recommended to push the env file to the git repository.

In our post, we are using the .env file inside the Python Flask application.

Inside your virtual environment of the project,

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

Reads the key-value pair from the .env file and adds them to the environment variable. It is great for managing app settings during development and in production using 12-factor principles.

The most common usage consists of calling load_dotenv when the application starts, which will load environment variables from a file named .env in the current directory.

Create your .env file along-side your settings/config file.

.
├── .env
└── config.py
Enter fullscreen mode Exit fullscreen mode

Inside your config file, enter the following lines,

from dotenv import load_dotenv
load_dotenv()
Enter fullscreen mode Exit fullscreen mode

Now all your key=value pairs will be loaded into your application. You can use the variable as,

import os
SECRET_KEY = os.getenv("MY_SECRET")
Enter fullscreen mode Exit fullscreen mode

That's it you can now create .env file and use it across the flask application.

To learn how to dockerize react application visit - https://lagandlog.com/logs/how-to-dockerize-react-app

Happy coding 👾

Discussion (0)