Using Environment Variables in Python: Easy Quick Guide

What are environment variables?

Think of them like secret notes your programs can read. These notes hold important information like:

  • Website addresses for connecting to databases
  • Special settings to make your app run the way you want
  • Secret passwords for extra security

Why are environment variables important?

  • Make your app adaptable: Change settings without changing the actual code.
  • Simplify updates: All your settings are in one place.
  • Boost security: Keep your passwords and sensitive data hidden.
  • Smooth deployments: Run the same app in different environments (like testing vs. live website)

Why Use Environment Variables for Application Security and Flexibility?

Sensitive information like API keys and encryption keys are the essential for modern applications. Adding them directly within your code introduces several risks:

Security Vulnerabilities: Code must be frequently updated and shared across development teams. This exposes sensitive credentials within the code itself.
Open-Source Challenges: If you plan to make your code open-source, you can’t include these secrets without putting your application’s security at risk.


Environment variables offer a more secure and flexible way to handle this:

Isolated Storage: Environment variables reside outside of your source code, minimizing exposure.
Development Agility: Developers can work with the code without accessing the actual secret values.
Environment-Specific Settings: You can easily tailor values (keys, database URLs, etc.) to different environments like development, testing, and production.

  • Environment variables enhance application security.
  • They promote open-source initiatives.
  • They make your codebase more adaptable.

How to use it in python?

For example we have a location API key for generating users data from the IP address

this is the example without environment variable. The key is directly included in the code




import requests

LOCATION_API_KEY = "1234567890"

def get_location(ip_address):
	url = f"https://example.com/{ip_address}/json?token={LOCATION_API_KEY}"
	response = requests.get(url)
	data = response.json()
	country = data.get("country")
	print(country)


    
    

In the example we directly included the key with the source code. The API have call limits. So if it compromised we may have to pay more.

So we can store the key with this command

export LOCATION_API_KEY="1234567890"

We can later access the variable with this command

echo $LOCATION_API_KEY

Implement in python code.

In the code we get the variable securely with os.environ.get(‘LOCATION_API_KEY’) so if even we share the code we can keep the API key secret. Not only API key , you can store password and other sensitive and essential variables




import os
import requests

# Retrieve the LOCATION_API_KEY from environment variables
LOCATION_API_KEY = os.environ.get('LOCATION_API_KEY')

def get_location(ip_address):
	url = f"https://example.com/{ip_address}/json?token={LOCATION_API_KEY}"
	response = requests.get(url)
	data = response.json()
	country = data.get("country")
	print(country)


    
    


We can Store Environment Variable from python code directly




import os

# Set the LOCATION_API_KEY environment variable
os.environ['LOCATION_API_KEY'] = '1234567890'

# Store other essential code like
os.environ['ADMIN_PASSWORD'] = '123456789101112'


# Retrieve the variable when needed
admin_password = os.environ.get('ADMIN_PASSWORD')
print(admin_password)



Related Posts

Print with python f string format
July 3, 2024

We use make the python print more wonderful with f string (formatted string) x=1 y=2 z=x+y print(f’result {x}+{y}={z}’) Copy Code this will print We can make it more wonderful directly adding expression x=1 y=2 print(f'{x} times {y} is {x * y}’) Copy Code We can also set the decimal places in the print number = […]

Check if a key exist or not in a python dictionary
July 3, 2024

We can check it with “in” operator and “get()” method In operator here returns the value True or False For example dictionary={“one”:1, “two”:2} if “two” in dictionary: print(“two exist in the dictionary”) Copy Code The get() method returns the value if that key exists. If not exists it returns None dictionary_data={“one”:1, “two”:2} #Here the key […]

Find out median of a list with python
July 3, 2024

Python has wonderful built-in library “statistics” We can find out the median of a list with this library easily with less code import statistics List = [1,2,3,4,5,6,7,8,9,10] result= statistics.median(List) print(result) Copy Code We can also generate list randomly with random module List = [randint(1, 101) for _ in range(50)] this code create a list of […]