Spaces:
Sleeping
Sleeping
File size: 1,916 Bytes
d57efd6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import OperationalError
from config import MYSQL_CONFIG
from fastapi import HTTPException
import os
import base64
SQLALCHEMY_DATABASE_URL = MYSQL_CONFIG.DB_URI_SQL_ALCHEMY
# Get the base64 encoded certificate from the environment variable
ca_cert_base64 = os.getenv("CA_CERT_BASE64")
# Decode the base64 content
if ca_cert_base64:
ca_cert_content = base64.b64decode(ca_cert_base64).decode("utf-8")
# Write the decoded content to a temporary .pem file
with open("/tmp/ca.pem", "w") as f:
f.write(ca_cert_content)
ca_cert_path = "/tmp/ca.pem"
else:
raise ValueError("CA_CERT_BASE64 environment variable is not set")
# Use the decoded CA certificate in the SQLAlchemy engine
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={
"ssl": {
"sslmode": "REQUIRED",
"ca": ca_cert_path, # Path to the temporary CA certificate
# Add other SSL options as needed
}
},
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
except OperationalError as e:
# Log the error and raise HTTPException for FastAPI
print(f"An error occurred in get database sql alchemy.: {e}")
raise HTTPException(status_code=400, detail="Database connection error")
# Check if it's an authentication-related error
except Exception as e:
# Check if it's an authentication-related error
if "401" in str(e):
raise HTTPException(status_code=401, detail="Authentication failed")
else:
# For any other type of exception, raise a generic 400 error
print(f"An error occurred: {e}")
raise HTTPException(status_code=400, detail="An unexpected error occurred") |