Forums

Problem with Always-on tasks

I deploy my python project to paythonanywere. It start through Bash console without problem.. But when I try to start it through Always-on tasks I get mistake:

raise EnvError('Environment variable "{}" not set'.format(proxied_key or parsed_key)) Dec 8 11:50:50 environs.EnvError: Environment variable "BOT_TOKEN" not set

Why doesn't the same code run?

Where is BOT_TOKEN coming from?

From .env

When are env variables populated from .env?

This:

def load_config(path: str = None):
    env = Env()
    env.read_env(path)

    return Config(
        tg_bot=TgBot(
            token=env.str("BOT_TOKEN"),
            admin_ids=list(map(int, env.list("ADMINS"))),
            use_redis=env.bool("USE_REDIS"),
        ),
        db=DbConfig(
            host=env.str('DB_HOST'),
            password=env.str('DB_PASS'),
            user=env.str('DB_USER'),
            database=env.str('DB_NAME')
        ),
        misc=Miscellaneous()
    )

That seems to be showing how the values are extracted from environment variables into the config inside your code. But how do you load the contents of the .env file into the environment variables in the first place? Do you have something in your .bashrc to load them, for example?

To put it another way -- when you run your code from a Bash console, what do you do to load up the contents of .env before you run the code?

When I run code from Bash console I do nothing to load up the contents of .env and it is works...

Ok, what is Env and what is path that you pass to load_config is it absolute or relative?

I have main python file bot.py, parth of it:

from tgbot.config import load_config

async def main():
logging.basicConfig(
    level=logging.INFO,
    format=u'%(filename)s:%(lineno)d #%(levelname)-8s [%(asctime)s] - %(name)s - %(message)s',
)
logger.info("Starting bot")
config = load_config(".env")

also config.py:

def load_config(path: str = None):
env = Env()
env.read_env(path)

return Config(
    tg_bot=TgBot(
        token=env.str("BOT_TOKEN"),
        admin_ids=list(map(int, env.list("ADMINS"))),
        use_redis=env.bool("USE_REDIS"),
    ),
    db=DbConfig(
        host=env.str('DB_HOST'),
        password=env.str('DB_PASS'),
        user=env.str('DB_USER'),
        database=env.str('DB_NAME')
    ),
    misc=Miscellaneous()
)

file .env in the main directory

I'm still not sure what is Env() returning. Also, use absolute path here config = load_config(".env").

Thanks for all your answers

Hope you were able to solve the issue!