Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the availability of environment variables correctly?

I did a token check, if at least one token is missing, 'True' will not be. Now I need to deduce which variable is missing, how to do it?

PRACTICUM_TOKEN = os.getenv('PRACTICUM_TOKEN')
TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')


def check_tokens():
    """Checks the availability of environment variables."""
    ENV_VARS = [PRACTICUM_TOKEN, TELEGRAM_TOKEN, TELEGRAM_CHAT_ID]
    if not all(ENV_VARS):
        print('Required environment variables are missing:', ...)
    else:
        return True
like image 310
finegorko Avatar asked Oct 15 '25 02:10

finegorko


1 Answers

I might suggest putting these values inside a class. The check tokens method can be part of the class, and you can use __dict__ to dynamically get reference to all of the tokens you defined without having to duplicate code.

class Environment:
    def __init__(self):
        self.PRACTICUM_TOKEN = os.getenv('PRACTICUM_TOKEN')
        self.TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
        self.TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')

    def check_tokens(self):
        """Checks the availability of environment variables."""
        missing_vars = [var for var, value in self.__dict__.items() if not value]
        if missing_vars:
            print('Required environment variables are missing:', *missing_vars)
            return False
        else:
            return True

print(Environment().check_tokens())
like image 144
flakes Avatar answered Oct 17 '25 15:10

flakes