sqlalchemy.exc.ArgumentError: 无法加载插件:sqlalchemy.dialects:driver

60

我正在尝试运行 alembic 迁移,但当我运行时

alembic revision --autogenerate -m "Added initial tables"

它失败了,提示如下:
sqlalchemy.exc.ArgumentError: Can't load plugin: sqlalchemy.dialects:driver

数据库的 URL 地址是:

postgresql+psycopg2://dev:passwd@localhost/db

我甚至在我的虚拟环境中安装了psycopg2

$yolk -l
Flask-Login     - 0.1.3        - active
Flask-SQLAlchemy - 0.16         - active
Flask           - 0.9          - active
Jinja2          - 2.6          - active
Mako            - 0.7.3        - active
MarkupSafe      - 0.15         - active
Python          - 2.7.2        - active development (/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload)
SQLAlchemy      - 0.8.0        - active
Werkzeug        - 0.8.3        - active
alembic         - 0.4.2        - active
antiorm         - 1.1.1        - active
appscript       - 1.0.1        - active
distribute      - 0.6.27       - active
envoy           - 0.0.2        - active
osascript       - 0.0.4        - active
pep8            - 1.4.5        - active
pip             - 1.1          - active
psycopg2        - 2.4.6        - active
wsgiref         - 0.1.2        - active development (/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7)
yolk            - 0.4.3        - active

什么可能导致这个问题?

将 sqlalchemy.url 中的 driver:// 改为 mysql:// 或 sqlite://。 - Sérgio
我发现错误包括在alembic.ini / sqlalchemy.url以"driver:// ..."开头时,而不是像"postgresql"这样的实际驱动程序名称时,包括"sqlalchemy.dialects:driver"。 - undefined
11个回答

83
以下是如何生成这样的错误:

以下是如何生成这样的错误:

>>> from sqlalchemy import *
>>> create_engine("driver://")
Traceback (most recent call last):
... etc
sqlalchemy.exc.ArgumentError: Can't load plugin: sqlalchemy.dialects:driver

所以我想说,你实际上并没有使用你认为的PostgreSQL URL - 你可能正在调用某个默认生成的alembic.ini。


你说得对,我在某个地方搞错了(不确定是哪里),虽然被这个问题困扰着,但我已经能够推进流程了。请看一下这个链接https://dev59.com/3WUo5IYBdhLWcg3w7jAq,如果你有什么想法,请告诉我。非常感谢你的帮助。 - daydreamer
没有注意到alembic.ini文件被创建在alembic目录的父目录中。谢谢! - Karl Lorey
要动态设置数据库URL,请参考此答案:https://dev59.com/cWEh5IYBdhLWcg3wpE3w#27256675 - Astariul

19
对于那些没有注意到的人,"默认生成的alembic.ini"是在项目的根目录中。整个问题在于设置alembic.ini文件中的sqlalchemy.url配置参数。另外,它可以根据https://dev59.com/3WUo5IYBdhLWcg3w7jAq#15668175中的说明进行编程设置。

alembic.ini可以放在任何地方。而Mike的昵称只有3个z:d - Antti Haapala -- Слава Україні

10
请注意,该方案实际上并没有指定驱动程序,而是指定了方言:该方案的格式为方言://方言+驱动程序://
例如,连接到PostgreSQL数据库的正确URL应该以postgresql://开头(默认使用psycopg2),或者显式选择驱动程序(postgresql+psycopg2://或其他驱动程序)。
如果您只指定了psycopg2,将会出现错误。
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:psycopg2

针对Airflow(Celery)用户:https://dev59.com/Y1oU5IYBdhLWcg3wIkeI#39967889 - Kyle Bridenstine
1
@snakecharmerb 谢谢,我不确定它是否曾经正确过 :'D - undefined

2
为了以编程方式覆盖 alembic.ini 中的默认值,您可以在 alembic/env.py 中添加一行或两行代码:
+ import app

[...snip...]

  # this is the Alembic Config object, which provides
  # access to the values within the .ini file in use.
  config = context.config

+ config.set_section_option(
    config.config_ini_section, "sqlalchemy.url", app.settings.SQLALCHEMY_DATABASE_URL
)

在这里,import appapp.settings.SQLALCHEMY_DATABASE_URL需要替换为您自己应用程序特定的代码以检索URL。


1
connection_url=""  
#your database connection string here pulled from either environment variable , vaults or can be set directly

def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = connection_url 
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    configdict=config.get_section(config.config_ini_section)
    configdict.update({"sqlalchemy.url":connection_url})
    connectable = engine_from_config(
        configdict,
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection, target_metadata=target_metadata
        )

        with context.begin_transaction():
            context.run_migrations()

如果你想从Python文件本身读取连接URL而不是引用默认的配置文件alembic.ini。

1
我通过在notepad ++中打开alembic.ini并修改项目文件中的url变量(大约在第38行)来解决了这个问题。错误很可能是因为它在开头有驱动程序引起的。
例如,将此行重命名为
sqlalchemy.url = sqlite:///name_of_my_database.db

1
如果你按照正确的语法创建引擎,根据你选择的数据库,使用create_engine(f"<方言名称>+<驱动程序名称>://{self.user}:{self.password}@{self.host}:{self.port}/{self.database}),并且这里提供的任何其他建议都不能解决你的问题,那么你可以尝试下一段中提到的解决方法。
问题NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:\<方言名称\>.\<驱动程序名称\>可能是由于运行了不支持所需驱动程序的SQLAlchemy版本造成的。例如,SQLAlchemy 1.4.26支持这些PostgreSQL驱动程序。因此,解决方法如下:
  1. 查阅文档以获取所需方言支持的驱动程序信息。
  2. 然后卸载SQLAlchemy或有问题的驱动程序pip uninstall SQLAlchemy
  3. 强制pip安装特定版本的SQLAlchemy或备选驱动程序pip install SQLAlchemy==1.0.14

0

尝试使用这些命令安装缺失的软件包:

sudo apt-get install libpq-dev 
sudo pip install psycopg2 
sudo pip install redshift-sqlalchemy 
sudo pip install sqlparse

0
为了让 Teradata 查询在 Pyinstaller 生成的 .exe 上运行,我将我的引擎从 SQLAlchemy 更改为 Teradata。
import sqlalchemy as sa
user, pasw, hostname = UserName,Password, 'myurl.com'
# connect
td_engine = sa.create_engine('teradata://{}:{}@{}:22/'.format(user,pasw,hostname),echo=True)
df = pd.read_sql_query(query1,connect)

收件人:

import teradata
user, pasw, hostname = UserName,Password, 'myurl.com'
td = teradata.UdaExec (appName="test", version="1.0", logConsole=True)
td_engine = td.connect(method="odbc",system=hostname, username=user,password=pasw,driver="Teradata") 

-1

如果您安装了Anaconda,请卸载它。它会将您的MySQL连接器安装在Anaconda路径中,而您的代码可能正在查找Python路径。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接