sqlalchemy.exc.nosuchmoduleerror:

Cause of sqlalchemy.exc.nosuchmoduleerror: 

This problem of sqlalchemy.exc.nosuchmoduleerror: cant load plugin: sqlalchemy.dialects:postgres occurs while connecting the Postgres database with SQLAlchemy. This problem also occurs if you have already installed pyscopg2. The code of the error is: 

 

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)

The error is as follows: 

 

Solution

There is a variety of solutions for the above problem but the main solution to this problem is instead of postgres:/, the URI should begin with postgresql:/. Both were accepted by SQLAlchemy, but the latter no longer supports the Postgres name.

The name PostgreSQL must now be used in place of the deprecated Postgres dialect name, which was deleted in QLAlchemy 1.4. The portion of the URL before the http:// is the dialect. Deprecation warnings were displayed by SQLAlchemy 1.3 and earlier, but they were nonetheless accepted.

Change postgres:/ to postgresql:/ in the URL to fix this.

Currently, working with Heroku causes this error since Heroku utilizes Postgres in the DATABASE URL they offer, which is what you most likely use for SQLALCHEMY DATABASE URI. The Heroku dashboard variable can be updated to utilize Postgresql as a workaround until they change it. The code for the same is:

 

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`

 

One can also try this code if the above solutions are not working for them:

 

# production or dev DB
try:
    prodURI = os.getenv('DATABASE_URL')
    prodURI = prodURI.replace("postgres://", "postgresql://")
    app.config['SQLALCHEMY_DATABASE_URI'] = prodURI

except:
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///MYDATABASE'

 

 

Also Read: show-doc not working in ruby pry

 

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *