Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Could not locate a bind configured on mapper mapped class class->tablename, SQL expression or this Session.

# When working with FastAPI
# database.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

SQLALCHEMY_DATABASE_URL = "mysql://user:pwd@host:port/db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


# main.py

from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session

from database import SessionLocal
import schema

def get_db():
    # The important thing here is to create an instance of SessionLocal
    # from database.py not Session from sqlalchemy
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
        
@app.get("/user", response_model=schema.User)
def get_user(user_id: int, db: Session=Depends(get_db))
	user = crud.get_user(db, user_id=user_id)
    return user
 
PREVIOUS NEXT
Tagged: #Could #locate #bind #configured #mapper #mapped #class #SQL #expression
ADD COMMENT
Topic
Name
8+7 =