How to setup .env in Python
Tags: python, programming, tutorial, github
Published: 2023-01-20 20:01:52

## What is a .env file?

A `.env` is a simple file that you can create that can store and host environment variables. Environment variables offer a way for your application to store and access variables relating to the environment of your application.

This could be anything from API keys to login credentials and passwords or special flags that you pass to your application to indicate production or development builds. .env files should never be committed to your project and should remain local only. As long as your system is not compromised, your API keys will not be compromised either.

## Why use a .env file?

`.env` are used to store sensitive environment variables locally.

 This means you can store variables pertaining to the environment, such as production or development variables needed across your application. These types of variables include API keys and login credentials for database connections and other application sensitive information. 

## How to setup a .env file

1.To start using a `.env` simply create a file called `.env` in the root of your project.

2.Add the `.env` file to your `.gitignore` file. If you do not have a `.gitignore` you can download a [default Python .gitignore](https://raw.githubusercontent.com/github/gitignore/main/Python.gitignore). 

`.gitignore` should be located in the root of your project (same place as .env). 

The purpose of a `.gitignore` file is to prevent git from committing specific files that are listed in this file, hence the name `.gitignore` since it ignores any file or directory listed in this file.

3.Set your environment variables, API keys, and any sensitive information such as login credentials inside the `.env` file using the following format: 

```
DISCORD_API_TOKEN=<API_KEY>
DISCORD_USERNAME=<USERNAME>
DISCORD_PASSWORD=<PASSWORD>
```

Note the `<` and `>` delimiter just means you replace the contents of that with the actual API_KEY you desire to hide. An example of a `.env` file is listed below:

```
DISCORD_API_TOKEN=1234-1234-1234-1234
DISCORD_USERNAME=TotallyFakeUserName
DISCORD_PASSWORD=Passw0rd!
```

4.Before accessing the environment variable in our application we need to install a package that lets us locate and load the `.env` file.

For this, we'll use Python's package installer to retrieve the package [python-dotenv](https://pypi.org/project/python-dotenv/) for us, which will allow us to load our `.env` and access our variables within our application.

Simply install `python-dotenv` by using the following command in the terminal:

```bash
pip install python-dotenv
```

If this command does not work, you can try alternatively using `python -m pip install python-dotenv` to install the package.

5.Now that we have the correct package installed we can load the `.env` file into our application. 

Normally we would have to hardcode the location of our `.env` file, but luckily there is a package to automatically locate the .env file included in `python-dotenv`, this function is called `find_dotenv()` which attempts to find our `.env` within our project.

```python
from dotenv import load_dotenv, find_dotenv

# find the .env file and load it 
load_dotenv(find_dotenv())
```

6.At this point, we have our `.env` file loaded in memory, but we have no way of accessing the variables just yet. 

 Python has a built-in method for this. We'll be using the `os` package which is already included in Python. The [os](https://docs.python.org/3/library/os.html#os.getenv) package offers us a function called `getenv()` which will allow us to get our environment variables. 

```python
from os import getenv
from dotenv import load_dotenv, find_dotenv

# find the .env file and load it 
load_dotenv(find_dotenv()
# access environment variable 
token = getenv("DISCORD_BOT_TOKEN")
```

## What if you are creating an open source application that needs a .env file?

If you intend on making your project public but don't want to expose your API keys `.env` is still the solution. 

 A good practice is creating a `.env.example` file that you commit to your code base. This file should only be a template of the environment variables the user is required to input and should not actually contain any keys or sensitive data. So for our example, we would create a `.env.example` file with the following contents:

```
DISCORD_BOT_TOKEN=<API_KEY>
DISCORD_USERNAME=<USERNAME>
DISCORD_PASSWORD=<PASSWORD>
```
This can be safely committed to our project without exposing any sensitive information. 

 In your applications README you can indicate that a user needs to correctly set this file up and they can use the following command to create their own .env file from this template:

```bash
cp .env.example .env
```

This command simply copies the example `.env` file and creates an actual `.env` file, here the user can modify the `.env` file and add their credentials, API keys, etc without exposing it to the world since the .gitignore is set to ignore the `.env` file.

## .env Naming Conventions

1.`.env` should have variables capitalized. This allows for better code readability, this convention is common when it comes to naming constant variables. An example is:

Incorrect:
```
discord_bot_token=1234-1234-1234
```

Correct:
```
DISCORD_BOT_TOKEN=1234-1234-1234
```

2.`.env` should be as explicit as possible when it comes to its variables. For instance, the variable TOKEN=<API_KEY> can indicate any type of token, however, if we name the variable DISCORD_API_TOKEN=<API_KEY> it becomes clear what exactly we are describing.

3.`.env` does not need quotes for variables unless the variable contains special characters or spaces. An example of this is as follows:

```
DISCORD_BOT_TOKEN=1234-1345-5345-3453
```

However, the following below needs quotations surrounding the variable since it has special characters towards the end or it has a space.

```
DISCORD_BOT_TOKEN="c2RmZ2FmZ2FnYWRmZ2FkZ2RmZ2FkZg=="
USERNAME="Bob Doll"
```

If we do not surround the items in quotes for these instances, the DISCORD_BOT_TOKEN string has double == sign towards the end, which may confuse parsers for your .env similarly, spaces between items will get ignored and only the first characters will be printed, so if we do not include the quotes for the USERNAME variable, we will only get back the value Bob when trying to access the username instead of the full name Bob Doll.


## Full discord bot code example

👍 If you found this article helpful please drop a like on this.
❔If you have any other questions please comment below.

Source:
[Stop hardcoding API keys: how to secure your code from attackers](https://edgar.codes/stop-hardcoding-your-api-keys)

![An example of discord bot using .env file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1jcx4pd5gp6trdq23ns.png)

<a href="https://www.buymeacoffee.com/engineeredgar"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=engineeredgar&button_colour=FFDD00&font_colour=000000&font_family=Lato&outline_colour=000000&coffee_colour=ffffff" /></a>