# database.py import os from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # --- Database Configuration --- DATABASE_URL = "postgresql://postgres:password@192.168.1.204:5432/fuelprices" # Ensure this DATABASE_URL is correct for your setup (e.g., 'db' for Docker Compose, # 'host.docker.internal' or an IP for external DBs) # For your error, it seems you are trying to connect to 192.164.1.204 # --- SQLAlchemy Setup --- DB_CONNECT_TIMEOUT = 5 # Timeout in seconds try: engine = create_engine( DATABASE_URL, connect_args={"connect_timeout": DB_CONNECT_TIMEOUT} # You can also add other psycopg2 connection parameters here, e.g.: # "options": "-c statement_timeout=5000" # statement timeout in milliseconds ) # Test the connection early (optional, but good for immediate feedback) # with engine.connect() as connection: # print(f"Successfully connected to database with {DB_CONNECT_TIMEOUT}s timeout setting.") except Exception as e: print(f"Failed to create database engine: {e}") # Depending on your application structure, you might want to raise the exception # or handle it in a way that prevents the app from starting if the engine can't be created. raise SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() def init_db(): try: # Ensure all models are imported before this is called so Base.metadata is populated. # This usually happens in run.py or your main application script. Base.metadata.create_all(bind=engine) print(f"Database tables checked/created successfully (using {DB_CONNECT_TIMEOUT}s connection timeout).") except Exception as e: # The error you posted would likely be caught here if the engine was created # but the connection failed during create_all() print(f"Error creating database tables: {e}") raise