Gets the token from the RAGNAR_OPENAI_API_KEY in the .env file. It also checks the environment variables as a fallback.
(self)
| 77 | os.environ.pop(key, None) |
| 78 | |
| 79 | def get_token(self): |
| 80 | """ |
| 81 | Gets the token from the RAGNAR_OPENAI_API_KEY in the .env file. |
| 82 | It also checks the environment variables as a fallback. |
| 83 | """ |
| 84 | # 1. Check environment variable first (for already loaded envs) |
| 85 | token = os.environ.get('RAGNAR_OPENAI_API_KEY') |
| 86 | if token: |
| 87 | logger.info("Token found in process environment variables.") |
| 88 | return token |
| 89 | |
| 90 | # 2. If not in env, check .env file |
| 91 | if not os.path.exists(self.env_file_path): |
| 92 | logger.warning(f".env file not found at {self.env_file_path}") |
| 93 | return None |
| 94 | |
| 95 | with open(self.env_file_path, 'r') as f: |
| 96 | for line in f: |
| 97 | line = line.strip() |
| 98 | if line.startswith('RAGNAR_OPENAI_API_KEY='): |
| 99 | token = line.split('=', 1)[1] |
| 100 | logger.info("Token found in .env file.") |
| 101 | return token |
| 102 | |
| 103 | logger.info("RAGNAR_OPENAI_API_KEY not found in .env file.") |
| 104 | return None |
| 105 | |
| 106 | def save_token(self, token): |
| 107 | """ |