Read system environment variables with python-Part 2

Overview

Apply Read system environment variables with python-Part 1 to create a python program to get system environment variables.

Constitution

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.

Next challenge

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

Read system environment variables with python-Part 2
Set environment variables with lambda-uploader
Shell variables, environment variables
[Python] Get environment variables
What are environment variables?
Python environment with docker-compose
[For beginners] Read DB authentication information from environment variables
Read excel with openpyxl
Virtual environment with Python 3.6
mongodb access with pymongo
[Note] Operate MongoDB with Python
Basics of touching MongoDB with MongoEngine
Manipulating strings with pandas group by
Read system environment variables with python-Part 1
Read system environment variables with python-Part 2
Environment variables when using Tkinter
Read csv with python pandas
Easy tox environment with Jenkins
Read image coordinates with Python-matplotlib
Handle Go environment variables (viper)
Create an environment with virtualenv
Minimal website environment with django
Install Python environment with Anaconda
Manage python environment with virtualenv
What are environment variables? (Linux)
venv environment with windows powershell
Handle environment variables in Python
Build python3 environment with ubuntu 16.04
ML environment construction with Miniconda
HTTP environment variables in Flask
Prepare python3 environment with Docker
Build python environment with direnv
Presentation Support System with Python3
Switch virtual environment with jupyter
Read json data with python