0

file structure:

|_ login.py
|_ main.py
|_ .env

login.py has function called login() that logs user in and sets token in .env file. .env file gets updated, but when I try to access the new updated token in main.py it gives me old token.

login.py:

import os
from dotenv import load_dotenv, set_key

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path)

creds = {
    'token': os.environ.get('TOKEN', ''),
    'username': os.environ.get('USERNAME', ''),
    'password': os.environ.get('PASSWORD', ''),
    'base_url': os.environ.get('BASE_URL', '')
}

def api_login():
    req = requests.post(creds).json()
    set_key(dotenv_path, 'token', req.get('token')

main.py:

import os
import requests

from dotenv import load_dotenv

from login import login

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path)

creds = {
    'token': os.environ.get('TOKEN', ''),
    'username': os.environ.get('USERNAME', ''),
    'password': os.environ.get('PASSWORD', ''),
    'base_url': os.environ.get('BASE_URL', '')
}


def make_request():
    if creds['token'] == '':
        login()
    print(os.environ.get('TOKEN', ''))

The only way I am able to get new token is if I store value in os.environ['temp_token'] = req.get('token') in login() and access it os.environ['temp_token'] in main.py. The other way is to make login() return the new token.

Is there a way you can get updated values from .env file?

soul
  • 29
  • 9
  • Does `main.py` call code from `login.py`? I am not sure why do you need a `.env` file. – Hernán Alarcón Jul 18 '22 at 20:04
  • @HernánAlarcón I am storing user credentials in .env file. main.py calls login function from login.py to get new token if existing token is expired or is set to empty string. – soul Jul 18 '22 at 20:09
  • 1
    Wouldn't it be easier if you just keep the token in memory and always read it from there? If you still want to persist it to a file, that file could be read just once at the beggining and written whenever you log in again. – Hernán Alarcón Jul 18 '22 at 20:17

0 Answers0