sqlalchemy.exc.NoSuchModuleError:无法加载插件:sqlalchemy.dialects:postgres

Mah*_*ala 76 python postgresql sqlalchemy psycopg2 flask-sqlalchemy

我正在尝试使用 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)
Run Code Online (Sandbox Code Playgroud)

Lea*_*ima 118

URI 应该以postgresql://而不是开头postgres://。SQLAlchemy 过去接受两者,但已取消对postgres名称的支持。

  • “postgres”已于 2009 年被弃用,并且 SQLAlchemy 从 v0.6 到 v1.3 发出了弃用警告。它最终在 2021 年的 v1.4 中被删除。请参阅 https://github.com/sqlalchemy/sqlalchemy/issues/6083#issuecomment-801478013 已弃用的命令已有 10 多年的支持。 (8认同)
  • 他们无缘无故破坏了多少个应用程序?荒谬的。https://en.wikipedia.org/wiki/Robustness_principle (2认同)

Git*_*son 70

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

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

这个错误目前在使用 Heroku 时出现,它postgresDATABASE_URL他们提供的SQLALCHEMY_DATABASE_URI. 要在他们更新之前解决此问题,请将 Heroku 仪表板中的变量更新为使用postgresql.

  • 多谢你们!我实际上最终联系了heroku,他们给了我这个解决了问题的文档(https://help.heroku.com/ZKNTJQSK/why-is-sqlalchemy-1-4-x-not-connecting-to-heroku-postgres )。Code: `uri = os.getenv("DATABASE_URL") # 或其他相关配置 var if uri.startswith("postgres://"): uri = uri.replace("postgres://", "postgresql:// ”, 1)` (15认同)
  • 如果您所说的变量是指配置变量,我尝试这样做并继续获取“项目无法更新:无法覆盖附件值 DATABASE_URL” (6认同)
  • @Daniyaldehleh 我在 Python 脚本中使用了一个简单的替换方法,而不是在 Heroku 仪表板中,因为正如您提到的那样,这不起作用。所以你可以这样做:`SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL?sslmode=require').replace('postgres://', 'postgresql://')`。 (6认同)
  • 添加上面的代码并尝试运行 app.py 后,输出以下错误: AttributeError: 'NoneType' object has no attribute 'replace' (2认同)

小智 28

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

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`
Run Code Online (Sandbox Code Playgroud)

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


Sou*_*ETO 10

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

  • 现有答案涵盖了将方言名称从 postgres 转换为 postgresql。指定驱动程序没有什么坏处,但与问题无关。 (3认同)