skip to Main Content

I get

File "C:PythonProjectsmyProjectroutershome.py", line 39, in

@router.get("/home", response_class=HTMLResponse)

raise TypeError(‘{!r} is not a callable object’.format(obj))
TypeError: <generator object get_db at 0x000002B68FBDB100> is not a
callable object

home.py

    from fastapi import Depends, APIRouter, Request
    from fastapi.templating import Jinja2Templates
    from sqlalchemy.orm import Session
    from starlette.responses import HTMLResponse
    
    from database import SessionLocal, engine
    from models import Base
    
    router = APIRouter()
    templates = Jinja2Templates(directory="templates", autoescape=False)
    Base.metadata.create_all(bind=engine)
    
    
    def get_db():
        try:
            db = SessionLocal()
            yield db
        finally:
            db.close()

@router.get("/home", response_class=HTMLResponse)
async def all_skills(request: Request, db: Session = Depends(get_db())):
    all = db.query()
    return templates.TemplateResponse("home.html", {"request": request, "show": all})

database.py

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

SQL_ALCHEMY_DATABASE_URL = "postgresql://postgres:password@localhost/DatabaseName"

engine = create_engine(SQL_ALCHEMY_DATABASE_URL)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

main.py

from fastapi import FastAPI

import models
from database import engine
from routers import home
from starlette.staticfiles import StaticFiles


app = FastAPI()

models.Base.metadata.create_all(bind=engine)

app.mount("/static", StaticFiles(directory="static"), name="static")

app.include_router(home.router)

2

Answers


  1. you shouldn’t call function you want to use as dependency:

    Depends(get_db)
    

    instead of

    Depends(get_db())
    
    Login or Signup to reply.
  2. You to use as dependency

    @router.get("/home", response_class=HTMLResponse)
    async def all_skills(request: Request, db: Session = Depends(get_db)):
        all = db.query()
        return templates.TemplateResponse("home.html", {"request": request, "show": all})
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search