我试图将alembic与fastapi和postgres sql一起使用,但它给了我错误,没有名为'数据库的模块,但它存在于项目中



当我运行alembic--autogenerate命令时,它会给我这个错误。它给出的错误是没有找到模块名称数据库,但存在database.py文件,并给出了这个错误。

这是我的env文件,当我在该文件中使用alembic时,由于该文件而发生错误从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导入clarative_base从sqlalchemy.orm导入sessionmaker#从配置导入设置

# 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:UsersMuzairDesktopFAwithFCC>alembic current
Traceback (most recent call last):
File "C:UsersMuzairAppDataLocalProgramsPythonPython310librunpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:UsersMuzairAppDataLocalProgramsPythonPython310librunpy.py", line 86, in _run_code
exec(code, run_globals)
File "C:UsersMuzairDesktopFAwithFCCvenvScriptsalembic.exe__main__.py", line 7, in <module>
File "C:UsersMuzairDesktopFAwithFCCvenvlibsite-packagesalembicconfig.py", line 588, in main
CommandLine(prog=prog).main(argv=argv)
File "C:UsersMuzairDesktopFAwithFCCvenvlibsite-packagesalembicconfig.py", line 582, in main
self.run_cmd(cfg, options)
File "C:UsersMuzairDesktopFAwithFCCvenvlibsite-packagesalembicconfig.py", line 559, in run_cmd
fn(
File "C:UsersMuzairDesktopFAwithFCCvenvlibsite-packagesalembiccommand.py", line 543, in current
script.run_env()
File "C:UsersMuzairDesktopFAwithFCCvenvlibsite-packagesalembicscriptbase.py", line 563, in run_env
util.load_python_file(self.dir, "env.py")
File "C:UsersMuzairDesktopFAwithFCCvenvlibsite-packagesalembicutilpyfiles.py", line 92, in load_python_file
module = load_module_py(module_id, path)
File "C:UsersMuzairDesktopFAwithFCCvenvlibsite-packagesalembicutilpyfiles.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:UsersMuzairDesktopFAwithFCCalembicenv.py", line 7, in <module>
from app.models import Base
File "C:UsersMuzairDesktopFAwithFCC.appmodels.py", line 6, in <module>
from database import Base
ModuleNotFoundError: No module named 'database'

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

您可能已经在/app文件夹中初始化了alembic,这不是问题,但处理起来很麻烦。该错误源于alembic未生成包的事实。

要修复您的错误,您可以删除您的alembic文件夹,然后在/app文件夹所在的同一级别上重新命名alembic。通过这样做,您可以查看fastapi官方演示项目的总体项目结构https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app

或者您执行alembic时,将PYTHONPATH设置为指向应用程序文件夹的根目录。

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

请参阅:使用Alembic时导入应用程序会引发ImportError

您也可以通过使用操作系统并将您的路径添加到sys 来修复错误

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

最新更新