Load .env before app imports to ensure environment variables are available
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 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,13 @@ from dotenv import load_dotenv
|
|||||||
import uvicorn
|
import uvicorn
|
||||||
from threading import Thread
|
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
|
# Telegram imports
|
||||||
from telegram.ext import (
|
from telegram.ext import (
|
||||||
Application,
|
Application,
|
||||||
@@ -61,13 +68,9 @@ logging.basicConfig(
|
|||||||
)
|
)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Load environment variables
|
# Environment variables (already loaded above)
|
||||||
env_path = Path(__file__).parent.parent / '.env'
|
|
||||||
load_dotenv(env_path)
|
|
||||||
|
|
||||||
# Environment variables
|
|
||||||
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
|
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'))
|
INTERNAL_API_PORT = int(os.getenv('INTERNAL_API_PORT', '8002'))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user