[Python] I'm trying to connect to a PostgreSQL database using SQLAlchemy in my FastAPI...

Discussão em 'Python' iniciado por Stack, Julho 13, 2025.

  1. Stack

    Stack Membro Participativo

    (Background on this error at: https://sqlalche.me/e/20/e3q8)

    Here's my database.py code:


    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    from dotenv import load_dotenv
    import os

    # Load environment variables from .env
    load_dotenv(os.path.join(os.path.dirname(__file__), '.env'))

    # Get the database URL from the environment
    SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL")

    # Setup engine and session
    engine = create_engine(SQLALCHEMY_DATABASE_URL)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    Base = declarative_base()

    DATABASE_URL=postgresql+psycopg2://username:password@host:port/dbname

    PythonPractice/
    └── app/
    ├── main.py
    ├── database.py
    ├── .env
    └── ...

    Continue reading...

Compartilhe esta Página