在 Python 中使用 Testcontainers-postgres 时出现 No module name 'psycopg2' 错误

问题描述 投票:0回答:1

我有一个如下所示的 session.py 文件:

"""Session module to create a session for the PostgreSQL database."""
from os import environ  # pylint: disable=no-name-in-module

from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
from testcontainers.postgres import PostgresContainer  # type: ignore

if environ.get("PYTHON_ENV") == "test":
    with PostgresContainer(image="postgres:13") as _postgres:
        DATABASE_URL = _postgres.get_connection_url()
else:
    DATABASE_URL = environ.get("DATABASE_URL", "")

print(f"DATABASE_URL: [{DATABASE_URL}]")
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


# pylint: disable=too-few-public-methods
class Base(DeclarativeBase):
    """Base class for the database models.

    This is used instead of declarative_base() because typing tools understand it.
    https://docs.sqlalchemy.org/en/20/changelog/whatsnew_20.html#step-one-orm-declarative-base-is-superseded-by-orm-declarativebase
    """

我正在使用以下工具:

  1. 依赖管理和打包的诗歌。
  2. 裤子作为构建系统。
  3. CI 管道的 Github Actions。
  4. Testcontainers-postgres 用于在 CI 管道中运行测试。
  5. Python 快速 API

问题出在测试工作流程中,我通过命令运行:

裤子测试:: 错误是: 引擎 = create_engine(DATABASE_URL) /home/runner/.cache/pants/named_caches/pex_root/venvs/s/c7e9f9b3/venv/lib/python3.11/site-packages/sqlalchemy/util/deprecations.py:281:警告中 return fn(*args, **kwargs) # 类型:忽略[no-any-return] /home/runner/.cache/pants/named_caches/pex_root/venvs/s/c7e9f9b3/venv/lib/python3.11/site-packages/sqlalchemy/engine/create.py:599:在create_engine中 dbapi = dbapi_meth(**dbapi_args) /home/runner/.cache/pants/named_caches/pex_root/venvs/s/c7e9f9b3/venv/lib/python3.11/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py:690:在 import_dbapi 中 导入psycopg2 E ModuleNotFoundError:没有名为“psycopg2”的模块

我不确定为什么会出现这种情况,因为 psycopg2 包含在我的 .toml 和 .lock 文件中。我什至运行了一个新的 CI 工作流程,其中我使用 pip 显式安装 psycopg2,但我遇到了相同的错误。

python sqlalchemy psycopg2 python-poetry testcontainers
1个回答
0
投票

我可以通过在上面为 session.py 共享的代码中添加 import psycopg2 来解决此问题。

import psycopg2  # type: ignore # noqa # pylint: disable=unused-import

我现在收到另一个错误,本地主机连接被拒绝连接到 postgres 测试容器。但由于这是一个不同的问题,我会将其标记为已解决。

© www.soinside.com 2019 - 2024. All rights reserved.