From 20f6c52785877d4fa50f3a81042cce08f8a06f61 Mon Sep 17 00:00:00 2001 From: Marius Mutu Date: Mon, 27 Oct 2025 00:43:57 +0200 Subject: [PATCH] Load .env before app imports to ensure environment variables are available MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move load_dotenv() call before all app.* imports in main.py to fix the import-time environment variable loading issue. Problem: - Previously, load_dotenv() was called AFTER importing app.* modules - When app.api.client was imported, it read BACKEND_URL at import time - At that moment, .env was not yet loaded, so it used the hardcoded default - This caused the bot to connect to wrong backend port even when .env was correctly configured Solution: - Move load_dotenv() to line 20-21, immediately after standard library imports - This ensures .env is loaded BEFORE any app.* modules are imported - Now all modules see the correct environment variables from .env file - Also updated BACKEND_URL default from 8001 to 8000 for consistency Flow now: 1. Import standard libraries (os, Path, dotenv, etc.) 2. Load .env file (line 20-21) ✅ 3. Import app.* modules (which can now read env vars correctly) ✅ 4. Import telegram-python-bot and other dependencies 5. Start application This follows Python best practices for environment variable loading and ensures reliable configuration loading in Windows Service deployments. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- reports-app/telegram-bot/app/main.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/reports-app/telegram-bot/app/main.py b/reports-app/telegram-bot/app/main.py index 0d9130a..4467546 100644 --- a/reports-app/telegram-bot/app/main.py +++ b/reports-app/telegram-bot/app/main.py @@ -13,6 +13,13 @@ from dotenv import load_dotenv import uvicorn from threading import Thread +# ============================================================================ +# LOAD ENVIRONMENT VARIABLES FIRST - BEFORE ANY APP IMPORTS +# ============================================================================ +# This ensures all modules can access environment variables at import time +env_path = Path(__file__).parent.parent / '.env' +load_dotenv(env_path) + # Telegram imports from telegram.ext import ( Application, @@ -61,13 +68,9 @@ logging.basicConfig( ) logger = logging.getLogger(__name__) -# Load environment variables -env_path = Path(__file__).parent.parent / '.env' -load_dotenv(env_path) - -# Environment variables +# Environment variables (already loaded above) TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN') -BACKEND_URL = os.getenv('BACKEND_URL', 'http://localhost:8001') +BACKEND_URL = os.getenv('BACKEND_URL', 'http://localhost:8000') INTERNAL_API_PORT = int(os.getenv('INTERNAL_API_PORT', '8002'))