当我运行alembic -autogenerate命令时,它会给出这个错误。给出了未发现模块名数据库但存在database.py文件的错误,并给出了该错误。

这是我的env文件,当我在这个文件中使用alembic时,会出现一个错误--从app.models导入基础导入app.config导入设置文件--因此它给出了一个错误,即在这些文件中数据库和配置模块不存在,但是它存在于其中。env.py:

from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context
from app.models import Base
from app.config import setting

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option("sqlalchemy.url", f'postgresql://{setting.database_username}:{setting.database_password}@{setting.database_hostname}:{setting.database_port}/{setting.database_name}')

# config.set_main_option("sqlalchemy.url", 'postgresql://postgres:uxairkhan@localhost/alembic')

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


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 = config.get_main_option("sqlalchemy.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.

    """
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        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()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

database.py:这是database.py文件,在这个文件中,它表示配置不存在,models.py文件中也发生了相同的错误,即没有模块数据库。从sqlalchemy导入create_engine,从sqlalchemy.ext.declarative导入declarative_base,从sqlalchemy.orm导入会话制造者#从配置导入设置

# SQLALCHEMY_DATABASE_URL = 'postgres://<username>:<password>@<ip-address/hostname>/<database-name>'
# SQLALCHEMY_DATABASE_URL = f'postgresql://{setting.database_username}:{setting.database_password}@{setting.database_hostname}:{setting.database_port}/{setting.database_name}'

engine  = create_engine(SQLALCHEMY_DATABASE_URL)

SessionLocal = sessionmaker(autocommit=False , autoflush=False , bind=engine)
                
Base = declarative_base()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

错误:

    (venv) C:\Users\Muzair\Desktop\FAwithFCC>alembic current
Traceback (most recent call last):
  File "C:\Users\Muzair\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\Muzair\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\Muzair\Desktop\FAwithFCC\venv\Scripts\alembic.exe\__main__.py", line 7, in <module>
  File "C:\Users\Muzair\Desktop\FAwithFCC\venv\lib\site-packages\alembic\config.py", line 588, in main
    CommandLine(prog=prog).main(argv=argv)
  File "C:\Users\Muzair\Desktop\FAwithFCC\venv\lib\site-packages\alembic\config.py", line 582, in main
    self.run_cmd(cfg, options)
  File "C:\Users\Muzair\Desktop\FAwithFCC\venv\lib\site-packages\alembic\config.py", line 559, in run_cmd
    fn(
  File "C:\Users\Muzair\Desktop\FAwithFCC\venv\lib\site-packages\alembic\command.py", line 543, in current
    script.run_env()
  File "C:\Users\Muzair\Desktop\FAwithFCC\venv\lib\site-packages\alembic\script\base.py", line 563, in run_env
    util.load_python_file(self.dir, "env.py")
  File "C:\Users\Muzair\Desktop\FAwithFCC\venv\lib\site-packages\alembic\util\pyfiles.py", line 92, in load_python_file
    module = load_module_py(module_id, path)
  File "C:\Users\Muzair\Desktop\FAwithFCC\venv\lib\site-packages\alembic\util\pyfiles.py", line 108, in load_module_py
    spec.loader.exec_module(module)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Muzair\Desktop\FAwithFCC\alembic\env.py", line 7, in <module>
    from app.models import Base
  File "C:\Users\Muzair\Desktop\FAwithFCC\.\app\models.py", line 6, in <module>
    from database import Base
ModuleNotFoundError: No module named 'database'

我在文档中搜索这个错误,我花了3天的时间,但是我没有找到任何解决方案。

原文
Stack Overflow用户修改于2022-03-07 10:37

广告关闭

618夏日盛惠

2核2G云服务器首年95元,GPU云服务器低至9.93元/天,还有更多云产品低至0.1折…

1 个回答

高票数最新
Stack Overflow用户

回答于2022-07-22 20:03

得票数 0

您可能已经在您的/app文件夹中添加了alembic,这不是一个问题,但是处理起来很麻烦。此错误源于以下事实: alembic不生成包。

要修复您的错误,您可以删除您的alembic文件夹,并在您的/app文件夹所在的同一级别上重新设置alembic。这样,您就可以查看快速you https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app官方演示项目的一般项目结构。

或者使用指向应用程序文件夹根目录的一组PYTHONPATH执行alembic。

PYTHONPATH=/absolute/path/toyourproject/ alembic revision --autogenerate -m "name"

请参阅:Importing app when using Alembic raises ImportError

还可以通过使用os并将路径添加到sys来修复错误。

请参阅:https://github.com/grillazz/fastapi-sqlalchemy-asyncpg/blob/main/alembic/env.py

发表评论

邮箱地址不会被公开。 必填项已用*标注