-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
37 lines (32 loc) · 1010 Bytes
/
database.py
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
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from config import DB_CONFIG, TESTING
from models import Base
import time
if TESTING:
DATABASE_URL = 'sqlite:///:memory:'
else:
DATABASE_URL = f"mysql+pymysql://{DB_CONFIG['user']}:{DB_CONFIG['password']}@{DB_CONFIG['host']}/{DB_CONFIG['database']}"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)
def init_db():
if TESTING:
Base.metadata.create_all(bind=engine)
return
retries = 5
for i in range(retries):
try:
Base.metadata.create_all(bind=engine)
print("Database initialized successfully.")
break
except Exception as e:
print(f"Database connection failed: {e}. Retrying in 5 seconds...")
time.sleep(5)
else:
raise Exception("Could not connect to the database after retries.")
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()