Spaces:
Runtime error
Runtime error
acecalisto3
commited on
Commit
•
778f8f1
1
Parent(s):
394c6d9
Update app2.py
Browse files
app2.py
CHANGED
@@ -34,6 +34,56 @@ class Settings(BaseSettings):
|
|
34 |
|
35 |
settings = Settings()
|
36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
# --- Database Model (Example) ---
|
38 |
class Article:
|
39 |
def __init__(self, title, url, content, timestamp):
|
|
|
34 |
|
35 |
settings = Settings()
|
36 |
|
37 |
+
# --- Database Connection ---
|
38 |
+
def get_db_url(settings: Settings) -> str:
|
39 |
+
if settings.DATABASE_TYPE == "mysql":
|
40 |
+
return f"mysql+aiomysql://{settings.DATABASE_USER}:{settings.DATABASE_PASSWORD}@{settings.DATABASE_HOST}:{settings.DATABASE_PORT}/{settings.DATABASE_NAME}"
|
41 |
+
elif settings.DATABASE_TYPE == "postgresql":
|
42 |
+
return f"postgresql+asyncpg://{settings.DATABASE_USER}:{settings.DATABASE_PASSWORD}@{settings.DATABASE_HOST}:{settings.DATABASE_PORT}/{settings.DATABASE_NAME}"
|
43 |
+
else:
|
44 |
+
return "sqlite+aiosqlite:///default.db"
|
45 |
+
|
46 |
+
async def set_db_connection(
|
47 |
+
db_type: str = None,
|
48 |
+
db_host: str = None,
|
49 |
+
db_port: int = None,
|
50 |
+
db_user: str = None,
|
51 |
+
db_password: str = None,
|
52 |
+
db_name: str = None
|
53 |
+
):
|
54 |
+
global db_session, engine, settings
|
55 |
+
try:
|
56 |
+
# Update settings if new values provided
|
57 |
+
if db_type:
|
58 |
+
settings.DATABASE_TYPE = db_type
|
59 |
+
if db_host:
|
60 |
+
settings.DATABASE_HOST = db_host
|
61 |
+
if db_port:
|
62 |
+
settings.DATABASE_PORT = db_port
|
63 |
+
if db_user:
|
64 |
+
settings.DATABASE_USER = db_user
|
65 |
+
if db_password:
|
66 |
+
settings.DATABASE_PASSWORD = db_password
|
67 |
+
if db_name:
|
68 |
+
settings.DATABASE_NAME = db_name
|
69 |
+
|
70 |
+
# Close existing connection if any
|
71 |
+
if db_session:
|
72 |
+
await db_session.close()
|
73 |
+
if engine:
|
74 |
+
await engine.dispose()
|
75 |
+
|
76 |
+
# Create new connection
|
77 |
+
db_url = get_db_url(settings)
|
78 |
+
engine = create_async_engine(db_url, echo=False)
|
79 |
+
async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
80 |
+
db_session = async_session_maker()
|
81 |
+
logger.info("Database connection established.")
|
82 |
+
return "Database connection established."
|
83 |
+
except Exception as e:
|
84 |
+
logger.error(f"Failed to establish database connection: {e}")
|
85 |
+
return f"Failed to connect to database: {e}"
|
86 |
+
|
87 |
# --- Database Model (Example) ---
|
88 |
class Article:
|
89 |
def __init__(self, title, url, content, timestamp):
|