Using Environment Variables in your Code
-
Introduction
- What is an environment variable?
- Setting environment variables
- Using enviroment variables in Java
- Using enviroment variables in Python
- Best practices
-
Environment variables
Environment variables…
-
Setting environment variables:
There are a few ways to set an environent variable:
- Adding to bash file: Edit your .zshrc file (or .bashrc for bash shell) and add the key/value pair as follows:
#list of environment variables
DB_URL=jdbc:mysql://localhost:3306/mydatabase
DB_USER=mydbuser
DB_PASSWORD=GimmeTheData2030
-
Using environment variables in Java:
public class AccessEnvironementVars {
public static void main(String[] args) {
String dbUrl = System.getenv("DB_URL");
if (dbUrl != null) {
System.out.println("Database URL: " + dbUrl);
} else {
System.out.println("Environment variable DB_URL not found.");
}
}
}
-
Using environment variables in Python:
To use environment variables in Python, you can leverage the os module:
Accessing an environment variable:
import os
# Get the value of the environment variable named 'MY_VARIABLE'
my_var = os.environ.get('MY_VARIABLE')
if my_var:
print(my_var)
else:
print("Environment variable 'MY_VARIABLE' not found.")
Output:
Environment variable 'MY_VARIABLE' not found.
-
Setting an environment variable:
import os
# Set the value of the environment variable 'MY_VARIABLE'
os.environ['MY_VARIABLE'] = 'Hello, World!'
# Access the newly set variable
print(os.environ.get('MY_VARIABLE'))
Output:
Hello, World!
-
Important considerations:
Security:
- Avoid hardcoding sensitive information like API keys or database credentials in your code. Instead, store them as environment variables. .env files:
-
Consider using a library like python-dotenv to manage environment variables from a .env file. This makes it easier to manage and share environment variables across projects.
- Data
- Storage
- Central Point
- Manipulating data
- Relation databases
-
Process isolation:
Environment variables are specific to each process. If you set an environment variable in one Python script, it won’t be automatically available in another script.
-
Best Practices For Using Environment Variables in Python
Always add . env files to . … While defining variables use descriptive, all UPPERCASE names.
-
Good:
DEBUG=True LOGGING_VERBOSITY=3 -
Bad:
debug=True LV=3
-
Best Practices For Using Environment Variables in Java
-
Good:
DEBUG=True LOGGING_VERBOSITY=3 -
Bad:
debug=True LV=3