[Python] SessionLocal is not callable

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using fastapi to create a basic API to do some statistics from a postgres database.

    I have just started using sqlalchemy as I want to do connection pooling, and based off of my googling it seems the route to go down.

    I've implemented this in my main.py file,

    def get_db():
    try:
    db = SessionLocal()
    yield db
    finally:
    db.close()


    Then using depends from fastapi with my URL params,

    async def get_data(xxx ,db: SessionLocal = Depends(get_db)):
    conn = db()


    With the sessions function being,

    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker

    from environment.config import settings


    SQLALCHEMY_DATABASE_URL = settings.DATABASE_URL
    engine = create_engine(SQLALCHEMY_DATABASE_URL)

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


    I'm receiving a type error of SessionLocal not being callable, wondering what I'm missing here?

    The issue I was having was when testing the API against being called, multiple calls to the API were essentially recreating a connection to the database, which was super laggy just testing locally - so wanting to make that...well work :)

    Imports for Main.py


    from plistlib import UID
    import string
    from typing import Optional

    from pandas import concat

    from fastapi import FastAPI, HTTPException, Header,Depends

    from fastapi.middleware.cors import CORSMiddleware


    from pydantic import BaseModel

    from db.session import SessionLocal

    from biometrics.TaskGet import GetSentiment, GetScheduled, GetAllActualSubstance, GetEmotions

    import aggregate.biometric_aggregators as biometric_aggregators

    import os

    Continue reading...

Compartilhe esta Página