sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres

PythonPostgresqlSqlalchemyFlask SqlalchemyPsycopg2

Python Problem Overview


I'm trying to connect to a Postgres database with SQLAlchemy. I've installed psycopg2. However, I get the error sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres. How do I configure SQLAlchemy to connect to PostgreSQL?

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "postgres://username@localhost:5432/template1"

db = SQLAlchemy(app)

Python Solutions


Solution 1 - Python

The URI should start with postgresql:// instead of postgres://. SQLAlchemy used to accept both, but has removed support for the postgres name.

Solution 2 - Python

SQLAlchemy 1.4 removed the deprecated postgres dialect name, the name postgresql must be used instead now. The dialect is the part before the :// in the URL. SQLAlchemy 1.3 and earlier showed a deprecation warning but still accepted it.

To fix this, rename postgres:// in the URL to postgresql://.

This error currently shows up when working with Heroku, which uses postgres in the DATABASE_URL they provide, which you probably use for SQLALCHEMY_DATABASE_URI. To work around this until they update it, update the variable in the Heroku dashboard to use postgresql.

Solution 3 - Python

The problem in heroku have been resolved by using simple python url replace code

import os
import re

uri = os.getenv("DATABASE_URL")  # or other relevant config var
if uri and uri.startswith("postgres://"):
    uri = uri.replace("postgres://", "postgresql://", 1)
# rest of connection code using the connection string `uri`

source : https://help.heroku.com/ZKNTJQSK/why-is-sqlalchemy-1-4-x-not-connecting-to-heroku-postgres

Solution 4 - Python

To fix this, rename postgres:// in the URL to postgresql+psycopg2://.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaharsh GheewalaView Question on Stackoverflow
Solution 1 - PythonLeandro LimaView Answer on Stackoverflow
Solution 2 - PythonGitau HarrisonView Answer on Stackoverflow
Solution 3 - Pythonuser16018677View Answer on Stackoverflow
Solution 4 - PythonSouvenir MEGNIGBETOView Answer on Stackoverflow