There are environment variables set in the operating system (macos):
MYSQL_HOST="127.0.0.1"
MYSQL_DATABASE="invoice"
MYSQL_UID="dude"
MYSQL_PWD="pass1234"
I would like to build a list called db_config
such that the end result will look like:
db_config = {'host':"127.0.0.1", 'database':"invoice", 'user':"dude",
'password':"pass1234"}
(Note that the environment variable names differ from the keys in db_config
. db_config
will be used to pass database connection credentials, and the keys must be those listed in the above db_config
.)
I can "manually" set db_config
using:
db_config={'host':os.environ['MYSQL_HOST'], 'database':os.environ['MYSQL_DATABASE'],
'user':os.environ['MYSQL_UID'], 'password':os.environ['MYSQL_PWD']}
...but it seems like there should be a cleaner more pythonic way of doing this, but I can't figure it out.
The os. environ is an object that represents users' environment variables and their values. It gives you a dictionary with the user's environmental variable names as they keys and their values as the values. The dictionary supports all the operations of the dictionary data structure in Python.
How to Create a Dictionary in Python. A dictionary in Python is made up of key-value pairs. In the two sections that follow you will see two ways of creating a dictionary. The first way is by using a set of curly braces, {} , and the second way is by using the built-in dict() function.
To create a Dictionary, use {} curly brackets to construct the dictionary and [] square brackets to index it. Separate the key and value with colons : and with commas , between each pair. As with lists we can print out the dictionary by printing the reference to it.
To avoid the error you can use the dictionary’s get () method, which returns None when the requested key does not exist in the dictionary: Python also provides the os.getenv () function to access environment variables. This function works in a very similar way to the os.environ.get () method. Here is how to access a variable with it:
environ is a dictionary provided by the os module which contains all environment variables. On the above, I am trying to print some of the environment variables that were already been set on my computer.
Environment variables are values that are set outside the program and they directly affect the way running processes behave in a computer. In simple terms, Environment variables are managed and stored by an operating system so that any program can use access them. An environment variable is made up of a key-value pair format.
You can create a .env file in the root directory of each of your projects, and that way you can keep all the variables that are needed by each project neatly organized! The python-dotenv package allows a Python application to import variables defined in a .env file into the environment.
config = {
'host': 'MYSQL_HOST',
'database': 'MYSQL_DATABASE',
'user': 'MYSQL_UID',
'password': 'MYSQL_PWD'
}
db_config = {k: os.environ.get(v) for k, v in config.items()}
Depending on how you want to treat items that aren't in os.environ
, you can use a conditional dict comprehension to ignore them.
db_config = {k: os.environ.get(v) for k, v in config.items()
if v in os.environ}
You may wish to rename old_name
and new_name
in the code below; and if you are sure that the environment variables will be present or require them to be available for your code to work correctly, you can remove the if
section of the dictionary comprehension shown below:
import os
transformations = (
('MYSQL_HOST', 'host'),
('MYSQL_DATABASE', 'database'),
('MYSQL_UID', 'user'),
('MYSQL_PWD', 'password')
)
db_config = {
new_name: os.environ[old_name]
for old_name, new_name in transformations
if old_name in os.environ
}
all ENV variable related to MYSQL in one dict
import os
keys = dict(os.environ).keys()
dic = {}
for key in keys:
if 'MYSQL_' in key:
dic.update({key.split('MYSQL_')[1]:os.environ.get(key)})
print(dic)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With