skip to Main Content

I can’t connect to my database with SQLAlchemy. It throws an error that says:

E   sqlalchemy.exc.ArgumentError: Could not parse SQLAlchemy URL from string '
E   postgresql://[my_username]:[my_password]@localhost:5432/tugas1-law-db"

Here’s my database.py implementation on FastAPI, which closely follows the FastAPI official guide:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

import os
from dotenv import load_dotenv

load_dotenv()

# SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
SQLALCHEMY_DATABASE_URL = f"""
postgresql://[my_username]:{os.environ["POSTGRES_PASSWORD"]}@localhost:5432/tugas1-law-db"
"""

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

Base = declarative_base()

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

And here’s the full error stack:

ImportError while loading conftest '/home/[my_username]/notebin/test/conftest.py'.
test/conftest.py:16: in <module>
    from database import Base, get_db
database.py:14: in <module>
    engine = create_engine(
env/lib/python3.10/site-packages/sqlalchemy/util/deprecations.py:281: in warned
    return fn(*args, **kwargs)  # type: ignore[no-any-return]
env/lib/python3.10/site-packages/sqlalchemy/engine/create.py:546: in create_engine
    u = _url.make_url(url)
env/lib/python3.10/site-packages/sqlalchemy/engine/url.py:842: in make_url
    return _parse_url(name_or_url)
env/lib/python3.10/site-packages/sqlalchemy/engine/url.py:908: in _parse_url
    raise exc.ArgumentError(
E   sqlalchemy.exc.ArgumentError: Could not parse SQLAlchemy URL from string '
E   postgresql://[my_username]:[my_password]@localhost:5432/tugas1-law-db"
E   '

I’m currently on WSL Ubuntu, if that helps. I’ve checked that postgresql service is running and it is, I’ve checked that the credentials are correct and I can login to postgres through the terminal with no problem, I’ve checked that the database "tugas1-law-db" exists. I’ve also tried changing my SQLAlchemy URL to an online database, but that also fails for some reason. I’ve checked that the syntax of the url is correct, and actually when I run my project in a Windows device it has no problem running.

2

Answers


  1. You have extra linebreaks on your string because you have a multiline string created with """, and also an extra " in the end.

    >>> SQLALCHEMY_DATABASE_URL = f"""
    postgresql://[my_username]:[my_password]@localhost:5432/tugas1-law-db"
    """
    >>> SQLALCHEMY_DATABASE_URL
    'npostgresql://[my_username]:[my_password]@localhost:5432/tugas1-law-db"n'
    

    Either remove linebreaks (and the extra ") by using single quotes and moving all to the same line:

    SQLALCHEMY_DATABASE_URL = f"postgresql://[my_username]:{os.environ["POSTGRES_PASSWORD"]}@localhost:5432/tugas1-law-db"
    

    or just remove the extra " and strip() the extra newlines out of the string.

    SQLALCHEMY_DATABASE_URL = f"""
    postgresql://[my_username]:{os.environ["POSTGRES_PASSWORD"]}@localhost:5432/tugas1-law-db
    """
    engine = create_engine(SQLALCHEMY_DATABASE_URL.strip())
    
    Login or Signup to reply.
  2. As an alternative to string formatting, you can use URL.create() to construct your connection URL:

    from sqlalchemy import create_engine, URL
    
    SQLALCHEMY_DATABASE_URL = URL.create(
        "postgresql",
        username="my_username",
        password=os.environ["POSTGRES_PASSWORD"],
        host="localhost",
        port=5432,
        database="tugas1-law-db",
    )
    engine = create_engine(SQLALCHEMY_DATABASE_URL)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search