Setting Environment Variables from Command Line

Please follow and like us:

Passwords and keys should not be in GitHub projects! I know it seems like a hassle, but you should get into the habit of putting passwords and keys in a file that is not in your GitHub project. One way of doing this is to have a .env file. Env files are the method that I prefer to use to store keys and passwords. So, all files with the .env extension get excluded.
On the bottom line of your local .gitignore file, type,

*.env

Putting this in the .gitignore file will make GitHub ignore all .env files.

I go over the use of .env files in a previous article.

If you are learning, you can still use .env files without having the program use them directly. Instead, you can use command-line commands to set keys and passwords, and you can place these command-line commands in the .env file. Then you can copy and paste these commands into the command line each time you start your virtual environment.

Let’s say, for example, you sign up to use the Coinmarketcap API from the site, https://coinmarketcap.com/api/.

Set API Key from Command Line

You will get an API key. Like all API keys, this API limits how many calls you can make per minute. The free version allows up to 30 calls per minute.

Now that you have gotten the API key, you can create a .env file with the command line commands that will set the key. In this case,

export COINMARKETCAP_API_KEY=’place your API key here’

After you have set up the virtual environment, run the command above. This will set the COINMARKETCAP_API_KEY temporarily within the virtual environment. Notice the name of the API key follows the standard practice of naming environment variables in all caps.

To see if the environment variable is set, run the following command with the dollar sign before the variable’s name.

echo $COINMARKETCAP_API_KEY

Then, to get the environment variable within python, you can use the command,

key=os.environ.get(‘COINMARKETCAP_API_KEY’)

This statement sets the standard variable, key, equal to the environment variable COINMARKETCAP_API_KEY.

In my next article, I will cover the use of the Coinmarketcap API.

Please follow and like us: