shri-jai commited on
Commit
c08b0fe
·
1 Parent(s): c41db55

fix: improved response time async fix

Browse files
Files changed (2) hide show
  1. src/core/database.py +15 -22
  2. src/main.py +4 -1
src/core/database.py CHANGED
@@ -1,38 +1,31 @@
1
  from typing import AsyncGenerator
2
-
3
- from dotenv import load_dotenv
4
  from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
5
- from sqlmodel import SQLModel, create_engine
6
  from sqlmodel.ext.asyncio.session import AsyncSession
7
-
8
- from src.core import *
9
  from src.core.config import settings
10
 
11
- load_dotenv()
12
-
13
- engine = create_engine(
14
- settings.DATABASE_URL, echo=True
15
- ) # to false on prod just to chcek for now
16
 
17
  async_engine = create_async_engine(
18
- url=settings.ASYNC_DATABASE_URL, future=True, connect_args={"ssl": True}
 
 
 
 
 
 
19
  )
20
 
21
  async_session = async_sessionmaker(
22
- class_=AsyncSession, bind=async_engine, expire_on_commit=False
 
 
 
23
  )
24
 
25
-
26
- def init_db():
27
- SQLModel.metadata.create_all(engine)
28
-
29
 
30
  async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
31
  async with async_session() as session:
32
  yield session
33
-
34
-
35
- if __name__ == "__main__":
36
- print("Table creating")
37
- init_db()
38
- print("Table Created successfully!")
 
1
  from typing import AsyncGenerator
2
+ from sqlmodel import SQLModel
 
3
  from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
 
4
  from sqlmodel.ext.asyncio.session import AsyncSession
 
 
5
  from src.core.config import settings
6
 
 
 
 
 
 
7
 
8
  async_engine = create_async_engine(
9
+ settings.ASYNC_DATABASE_URL,
10
+ echo=False,
11
+ future=True,
12
+ pool_size=20,
13
+ max_overflow=40,
14
+ pool_timeout=30,
15
+ connect_args={"ssl": True},
16
  )
17
 
18
  async_session = async_sessionmaker(
19
+ async_engine,
20
+ class_=AsyncSession,
21
+ expire_on_commit=False,
22
+ autoflush=False
23
  )
24
 
25
+ async def init_db():
26
+ async with async_engine.begin() as conn:
27
+ await conn.run_sync(SQLModel.metadata.create_all)
 
28
 
29
  async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
30
  async with async_session() as session:
31
  yield session
 
 
 
 
 
 
src/main.py CHANGED
@@ -12,7 +12,10 @@ from fastapi.staticfiles import StaticFiles
12
 
13
  app = FastAPI(title="Yuvabe App API")
14
 
15
-
 
 
 
16
  app.include_router(home_router, prefix="/home", tags=["Home"])
17
 
18
  # init_db()
 
12
 
13
  app = FastAPI(title="Yuvabe App API")
14
 
15
+ @app.on_event("startup")
16
+ async def on_startup():
17
+ await init_db()
18
+
19
  app.include_router(home_router, prefix="/home", tags=["Home"])
20
 
21
  # init_db()