Multimedika/Bot_Development
0
1from sqlalchemy import create_engine2from sqlalchemy.orm import sessionmaker3from sqlalchemy.exc import OperationalError4from config import MYSQL_CONFIG5from fastapi.responses import JSONResponse6from fastapi import HTTPException, status7from dotenv import load_dotenv8import io9import os10import base6411 12load_dotenv()13 14SQLALCHEMY_DATABASE_URL = MYSQL_CONFIG.DB_URI_SQL_ALCHEMY15 16# Retrieve the Base64-encoded CA certificate from the environment variable17ca_cert_base64 = os.getenv("CA_CERT_BASE64")18 19if ca_cert_base64:20 # Decode the base64 content21 ca_cert_content = base64.b64decode(ca_cert_base64).decode("utf-8")22 23 # Use in-memory buffer to handle the decoded CA certificate content24 ca_cert_in_memory = io.StringIO(ca_cert_content)25 26 # Create SQLAlchemy engine with SSL configuration, using in-memory certificate27 engine = create_engine(28 SQLALCHEMY_DATABASE_URL,29 connect_args={30 "ssl": {31 "sslmode": "REQUIRED",32 "sslrootcert": ca_cert_in_memory, # In-memory CA certificate33 # Add other SSL options like client cert/key if required34 }35 },36 )37 38else:39 raise ValueError("CA_CERT_BASE64 environment variable is not set")40 41 42SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)43 44 45def get_db():46 db = SessionLocal()47 try:48 yield db49 except OperationalError as e:50 # Log the error and raise HTTPException for FastAPI51 print(f"An error occurred in get database sql alchemy.: {e}")52 raise HTTPException(status_code=400, detail="Database connection error")53 # Check if it's an authentication-related error54 except Exception as e:55 # Check if it's an authentication-related error56 if "401" in str(e):57 raise HTTPException(status_code=401, detail="Authentication failed")58 else:59 # For any other type of exception, raise a generic 400 error60 print(f"An error occurred: {e}")61 raise HTTPException(status_code=400, detail="An unexpected error occurred")