[英]SQL Alchemy - Base.metadata.create_all(bind=engine) not creating tables in test db
I am using FastAPI to build an API backend for my URL shortener.我正在使用 FastAPI 为我的 URL 缩短器构建 API 后端。 I have the database connected to the API as a dependency.
我将数据库作为依赖项连接到 API。 For the CRUD operations, I am using the SQL Alchemy ORM.
对于 CRUD 操作,我使用的是 SQL Alchemy ORM。
The code for my main app works perfectly fine and performs all the major CRUD operations I have mapped through the API endpoints.我的主应用程序的代码运行良好,并执行我通过 API 端点映射的所有主要 CRUD 操作。
The problem arises when I try to override the DB dependency to use a test db instead of my production db for testing purposes.当我尝试覆盖数据库依赖项以使用测试数据库而不是生产数据库进行测试时,就会出现问题。
There are no errors associated with this override, however, the test database does not contain any of the tables that would be created when Base.metadata.creat_all(bind=engine)
is called.没有与此覆盖相关的错误,但是,测试数据库不包含任何将在
Base.metadata.creat_all(bind=engine)
时创建的表。
When running the tests using pytest , it gives me this error:使用pytest运行测试时,它给了我这个错误:
sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1146, "Table 'testurldb.urls' doesn't exist")
The code for my tests:我的测试代码:
engine = create_engine(
"mysql+pymysql://{user}:{password}@{ip}:{port}/testurldb".format(
user=user, password=password, ip=ip, port=port
)
)
Session = sessionmaker(bind=engine)
Base.metadata.create_all(bind=engine)
def overrideDB():
db = Session()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = overrideDB
client = TestClient(app)
The module where Base is instantiated:实例化 Base 的模块:
engine = create_engine(
"mysql+pymysql://{root}:{password}@{ip}:{port}/urldb".format(
root=root, password=password, ip=ip, port=port
)
)
SessionLocal = sessionmaker(bind=engine)
Base = declarative_base()
The table that extends Base:扩展 Base 的表:
class URL(Base):
__tablename__ = "urls"
short_url = Column(String(256), primary_key=True, unique=True, nullable=False)
long_url = Column(String(256), nullable=False, unique=True)
time = Column(String(256), nullable=False)
def __init__(self, short_url, long_url, time):
self.short_url = short_url
self.long_url = long_url
self.time = time
There seems to be nothing wrong with the imports, so I don't understand why it's not creating the tables.导入似乎没有任何问题,所以我不明白为什么它不创建表。
And second, it might be useful information that my main production db already has the Tables created.其次,我的主要生产数据库已经创建了表,这可能是有用的信息。
Create a file and import all models into it, at the end of all imports, put the Model import.创建一个文件并将所有模型导入其中,在所有导入结束时,将 Model 导入。 When doing this, try to create the models again through Base.metadata
执行此操作时,尝试通过 Base.metadata 再次创建模型
i hope it'll helps you我希望它会帮助你
db.py数据库.py
Base = declarative_base()
async def init_db():
try:
Base.metadata.create_all(bind=engine)
except Exception as e:
raise e
main.py主文件
@app.on_event("startup")
async def on_startup():
await init_db()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.