Apply Read system environment variables with python-Part 1 to create a python program to get system environment variables.
EnvironWrapper.py
import os
class EnvironWrapper:
"""
class:EnvironWrapper
Overview:Class that holds startup parameters read from environment variables
"""
#Environment variable
defaultenv_context = {
"SECRET_KEY" : 'naishokey', # SECRET_KEY
"DEBUG_FLG" : 'true', # DEBUG_FLG
"ALLOWED_HOSTS" : None, # ALLOWED_HOSTS
}
#Environment variable
getenv_context = {}
def __init__(self):
"""
constructor
os.Read environment variables from environ
"""
for key, value in self.defaultenv_context.items():
param = os.getenv(key, default=value)
if key == "DEBUG_FLG" :
param = False if param.lower().startswith('false') else True
self.getenv_context[key] = param
def GetParams(self, key : str) -> object:
"""
GetParams:Environment variable acquisition process
Arguments:
key {str} --Environment variable key
Returns:
object --Environment variable value
"""
return self.getenv_context[key]
if __name__ == "__main__":
env = EnvironWrapper()
for key, value in env.getenv_context.items():
print(f"key:{key}, value:{value}")
System environment variables also include persistent data such as% USERNAME% for windows, and I want to limit it to only the system environment variables I need.
Define the system environment variables used in defaultenv_context
and their default values, and store the necessary system environment variables in getenv_context in a dictionary type.
Since ʻos.environ` is a dictionary type in the first place, it is named as a wrapper class of environ.
EnvironWrapperRun.bat
@ECHO OFF
ECHO <input value>
Read REM configuration file
FOR /F "usebackq delims== tokens=1,2" %%i IN ("setting.ini") do (
SET %%i=%%j
SET %%i
)
ECHO:
ECHO <acquired value>
python EnvironWrapper.py
EnvironWrapperRun.sh
#!/bin/bash
#Read configuration file
echo <input value>
while read line
do
export $line
echo $line
done < setting.ini
echo <acquired value>
python3 EnvironWrapper.py
setting.ini
SECRET_KEY=1234567890qwertyuiopasdfghjklzxcvbnm
DEBUG_FLG=True
ALLOWED_HOSTS=127.0.0.1
The system environment variables set this time are summarized in setting.ini so that they do not depend on the OS. Since the usage of system environment variables differs depending on the OS, the startup files are separated. Read setting.ini line by line in the startup file, set it in the system environment variable, and then execute the python program.
SET variable name = variable value
,% variable value%
,
$ variable value`,As you can see from the contents of setting.ini, it defines the setting values used in Django's setting.py. Consider a mechanism that allows DI at startup according to the development status (develop-staging-release) of the setting value of setting.py.
Recommended Posts