Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres: how to fix it

NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres means your database URL starts with postgres://, a name SQLAlchemy 1.4 and later no longer accept. Use postgresql://, or name the driver: postgresql+psycopg2:// or postgresql+psycopg://. When a host hands you a postgres:// DATABASE_URL, rewrite the scheme in code before create_engine.

By Livops team, the people who build and run LivopsUpdated

The app starts, reaches the line that creates the engine, and stops. With Flask-SQLAlchemy or plain create_engine, the last line of the traceback is the same:

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

SQLAlchemy builds this message from the plugin group it searched, sqlalchemy.dialects, and the name it looked for, postgres[3]. The name comes from the start of your database URL. This page explains why postgres:// stopped working, gives the fix for a URL you control and for one a host sets for you, and shows how to check it before you deploy again.

What does the error mean?

A SQLAlchemy URL has the form dialect+driver://username:password@host:port/database, where the dialect is a name such as postgresql, mysql or sqlite, and the driver is the Python package that talks to the database[5]. SQLAlchemy looks up the part before :// in its registry of dialects; when the URL has a +, it searches for dialect.driver[4]. A URL that starts with postgres:// asks for a dialect named postgres, and there is none, so the lookup ends with NoSuchModuleError[3].

There used to be one. SQLAlchemy 1.3 kept a translation from postgres to postgresql, and printed a deprecation warning that the postgres dialect name had been renamed[2]. SQLAlchemy 1.4 removed support for URLs of the form postgres://, with the note that this had emitted a warning for many years and projects should use postgresql://[1]. The removal is listed under 1.4.0b1, and 1.4.0 itself was released on 15 March 2021[1]. The current release on PyPI is 2.1.9[11], so every SQLAlchemy you install today refuses postgres://.

Where postgres:// comes from

  • The host. Heroku’s own documentation gives its Postgres DATABASE_URL the convention postgres://<username>:<password>@<host>/<dbname>[13]. Code that passes that variable straight to SQLAlchemy fails on any SQLAlchemy from 1.4 on.
  • Other tools accept it. libpq, the PostgreSQL client library under psql, takes either postgresql:// or postgres:// as the URI scheme[12]. So psql "$DATABASE_URL" connects, and only the app fails.
  • An old tutorial or .env. A URL written years ago, when SQLAlchemy 1.3 still translated it, keeps working until the next install pulls SQLAlchemy 1.4 or later.

The same error with another name

The error names What it means
sqlalchemy.dialects:postgres the URL starts postgres://
sqlalchemy.dialects:postgres.psycopg2 the URL starts postgres+psycopg2://; the dialect half is still the old name
sqlalchemy.dialects:postgresql.psycopg postgresql+psycopg:// on SQLAlchemy older than 2.0, which added the psycopg 3 dialect[7]

The . in place of + is how SQLAlchemy turns a URL’s dialect+driver into the name it searches for[4].

Fix 1: write postgresql:// where you control the URL

If the URL is in your own config or variables, change the scheme and keep the rest:

postgres://app:[email protected]:5432/app      # fails
postgresql://app:[email protected]:5432/app    # works

Better, name the driver too, so the URL does not depend on SQLAlchemy’s default:

URL starts with Driver package Notes
postgresql+psycopg2:// psycopg2 or psycopg2-binary SQLAlchemy 2.0’s default for postgresql://[5]
postgresql+psycopg:// psycopg (version 3) SQLAlchemy 2.0 and later[6][7]; the default for postgresql:// from 2.1[8]
postgresql+asyncpg:// asyncpg for create_async_engine[6]

The default changed between versions: in SQLAlchemy 2.0 a bare postgresql:// loads psycopg2[5], and in 2.1 it loads psycopg 3, while postgresql+psycopg2:// still selects psycopg2[8][9]. The psycopg2 dialect imports psycopg2 when the engine is created[10], so a bare URL with the other package installed stops on No module named 'psycopg2' instead. Naming the driver avoids that surprise after an upgrade. With psycopg 3, the same postgresql+psycopg:// URL works for both create_engine and create_async_engine[6].

Fix 2: rewrite the URL in code when a host sets it

When the platform writes DATABASE_URL for you and you cannot change its scheme, fix it where the app reads it, before it reaches SQLAlchemy:

import os

url = os.environ["DATABASE_URL"]
for old in ("postgres://", "postgresql://"):
    if url.startswith(old):
        url = "postgresql+psycopg://" + url[len(old):]
        break

Replace postgresql+psycopg with postgresql+psycopg2 if that is the driver in your requirements. The loop also gives a driver to a URL that already says postgresql://, so the same code works on any host. With Flask-SQLAlchemy, put the result in SQLALCHEMY_DATABASE_URI, the URI its default engine connects with[14]:

app.config["SQLALCHEMY_DATABASE_URI"] = url

In an Alembic env.py or a script, pass the same url to create_engine. If you already use SQLAlchemy’s URL object, make_url(url).set(drivername="postgresql+psycopg") changes only the scheme and returns a new URL[4].

Two things not to do:

  • Do not replace every postgres in the string. The user name or database name may contain it; change only the scheme at the start.
  • Do not build the URL by gluing a password in. A password with @ or / must be percent-encoded in a URL string; SQLAlchemy’s docs encode kx@jj5/g as kx%40jj5%2Fg[5]. If you assemble the URL from parts, use URL.create, which takes the password as plain text[5].

How to check the URL before you deploy

Test the exact value the app will read, without printing the password:

.venv/bin/python -c 'import os; from sqlalchemy import make_url; u = make_url(os.environ["DATABASE_URL"]); print(u.drivername, u.host, u.database)'

make_url only parses the string, so it prints postgres for an old URL without failing; the error comes later, when the dialect is looked up[4]. If the first word is postgres, apply Fix 1 or Fix 2. Then check that the engine loads:

.venv/bin/python -c 'import os, sqlalchemy as sa; e = sa.create_engine(os.environ["DATABASE_URL"].replace("postgres://", "postgresql://", 1)); print(e.dialect.name, e.dialect.driver)'

It prints the dialect and the driver, for example postgresql psycopg2, without connecting. If it says No module named, add that driver to requirements.txt; if it connects later and the server refuses the login, see password authentication failed.

On Livops

  • DATABASE_URL already starts with postgresql://. Add PostgreSQL in Databases, and its address is written to every service in the environment as DATABASE_URL=postgresql://app:<password>@postgres:5432/app, with PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE and the POSTGRES_* names beside it. SQLAlchemy reads that scheme as it is. A bare postgresql:// uses SQLAlchemy’s default driver, so have that driver in requirements.txt, or add +psycopg or +psycopg2 in code as in Fix 2.
  • An external database. If you bring a postgres:// URL from another provider, put it in Settings → Variables with the scheme already changed to postgresql://, or keep the rewrite from Fix 2 in code.
  • A changed variable needs a deploy. A new value takes effect on the next deploy; to apply it now, restart the service.
  • Where the error shows up. If the app stops at start-up on this error, the deploy fails as start_failed and the message is on the Logs page. If the URL is read by a migration in the pre-deploy command, the deploy fails as predeploy_failed and the new version is not started.
  • Installing the driver. psycopg2 compiles on install; Livops retries in an image with a compiler, and if it still fails, list psycopg2-binary instead, which needs no compiling.

A database is free at 500 MB, one per team; 1 GB is 9 credits a month. Everything about the database itself: PostgreSQL hosting and Databases.

Questions

Why did postgres:// work before and stop now?

SQLAlchemy 1.3 and older translated postgres to postgresql and printed a deprecation warning. SQLAlchemy 1.4 removed that translation, so an app that upgraded SQLAlchemy, often through an unpinned requirements.txt on a fresh deploy, now stops on the same URL.

Is there a setting that makes SQLAlchemy accept postgres:// again?

No. The alias was removed, not turned off. Change the scheme to postgresql://, either in the variable itself or in code before the URL reaches create_engine.

Why does psql accept the same URL?

libpq, which psql uses, accepts both postgresql:// and postgres:// as the scheme. SQLAlchemy reads the part before :// as the name of its dialect, and it has no dialect called postgres.

Which driver does postgresql:// with no driver use?

SQLAlchemy's default for PostgreSQL. In SQLAlchemy 2.0 that is psycopg2; in SQLAlchemy 2.1 it is psycopg, version 3. Name the driver in the URL, postgresql+psycopg2:// or postgresql+psycopg://, and the choice no longer depends on the SQLAlchemy version.

What about async SQLAlchemy?

create_async_engine needs an async driver in the URL: postgresql+asyncpg:// with asyncpg, or postgresql+psycopg:// with psycopg 3, which SQLAlchemy runs in async mode when the engine is async.

I now get Can't load plugin: sqlalchemy.dialects:postgresql.psycopg. What is that?

The same lookup with the driver part added: the dialect postgresql.psycopg does not exist in your SQLAlchemy. Support for psycopg 3 arrived in SQLAlchemy 2.0, so on 1.4 use postgresql+psycopg2:// or upgrade SQLAlchemy.

Which scheme does Livops give in DATABASE_URL?

postgresql://, for example postgresql://app:<password>@postgres:5432/app. SQLAlchemy accepts it as it is; add +psycopg or +psycopg2 in code if you want to name the driver.

Sources

  1. SQLAlchemy docs — 1.4 Changelog (docs.sqlalchemy.org). Checked .
  2. SQLAlchemy source — lib/sqlalchemy/dialects/__init__.py (rel_1_3) (raw.githubusercontent.com). Checked .
  3. SQLAlchemy source — lib/sqlalchemy/util/langhelpers.py (rel_2_0) (raw.githubusercontent.com). Checked .
  4. SQLAlchemy source — lib/sqlalchemy/engine/url.py (rel_2_0) (raw.githubusercontent.com). Checked .
  5. SQLAlchemy docs — Engine Configuration (2.0) (docs.sqlalchemy.org). Checked .
  6. SQLAlchemy docs — PostgreSQL dialect (2.0) (docs.sqlalchemy.org). Checked .
  7. SQLAlchemy docs — What's New in SQLAlchemy 2.0 (docs.sqlalchemy.org). Checked .
  8. SQLAlchemy docs — 2.1 Changelog (docs.sqlalchemy.org). Checked .
  9. SQLAlchemy source — lib/sqlalchemy/dialects/postgresql/__init__.py (2.1.9) (raw.githubusercontent.com). Checked .
  10. SQLAlchemy source — lib/sqlalchemy/dialects/postgresql/psycopg2.py (rel_2_0) (raw.githubusercontent.com). Checked .
  11. PyPI — SQLAlchemy (pypi.org). Checked .
  12. PostgreSQL docs — Database Connection Control Functions (connection strings) (postgresql.org). Checked .
  13. Heroku Dev Center — Connecting to Heroku Postgres (devcenter.heroku.com). Checked .
  14. Flask-SQLAlchemy docs — Configuration (flask-sqlalchemy.readthedocs.io). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy with a database

Got a question? — @livops_uz