121

我正在尝试使用 SQLAlchemy 连接到 Postgres 数据库。我已经安装了 psycopg2。但是,我得到了错误sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres。如何配置 SQLAlchemy 以连接到 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)
4

3 回答 3

196

URI 应该以postgresql://而不是postgres://. SQLAlchemy 曾经接受两者,但已删除对postgres名称的支持。

于 2020-11-05T14:08:30.913 回答
100

SQLAlchemy 1.4 删除了不推荐使用的postgres方言名称,postgresql现在必须使用该名称。方言是://URL 中的之前的部分。SQLAlchemy 1.3 及更早版本显示了弃用警告,但仍接受它。

要解决此问题,postgres://请将 URL 中的重命名为postgresql://.

当前使用 Heroku 时会出现此错误,该错误用于postgres他们DATABASE_URL提供的,您可能用于SQLALCHEMY_DATABASE_URI. 要在他们更新之前解决此问题,请将 Heroku 仪表板中的变量更新为使用postgresql.

于 2021-03-25T07:31:50.593 回答
19

通过使用简单的python url替换代码解决了heroku中的问题

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`

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

于 2021-05-29T18:51:38.130 回答