What if the database connection pool is not enough? #12179
-
First Check
Commit to Help
Example Codefrom fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from . import crud, models, schemas
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/users/", response_model=schemas.User)
async def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
db_user = crud.get_user_by_email(db, email=user.email)
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
return crud.create_user(db=db, user=user)
-----------------------------------------------------
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine(
"mysql+pymysql://username:password@localhost:port/test", pool_size=20, max_overflow=0, pool_pre_ping=True
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)Description
Operating SystemLinux Operating System DetailsNo response FastAPI Version0.87.0 Pydantic Version1.10.8 Python VersionPython 3.8.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
If you are using standard pool, you will probably be able to set the But be careful, at some point you can reach the limit of your server.
It's SQLAlchemy's pool that does it when you call
If you are talking about establishing new connection every time you need instead of using connection pool, then it's not very efficient way, because it takes time to establish new connection, and by using connection pool you can save this time. |
Beta Was this translation helpful? Give feedback.
If you are using standard pool, you will probably be able to set the
poollimits using the parameterspool_size(by default is 5) andmax_overflow(by default is 10): https://docs.sqlalchemy.org/en/20/core/engines.html#But be careful, at some point you can reach the limit of your server.
It's SQLAlchemy's pool that does it when you call
SessionLocal(in this case).If you are talking about establishing new connection every time you need instead of using connection pool, then it's not very efficient way, because it takes time to estab…