DIN*_*LIT 7 python sqlalchemy python-asyncio fastapi sqlmodel
我试图使用fastapi users包快速向使用 PostgreSQL 数据库的 FastAPI 项目添加注册和身份验证系统。我用来asyncio创建异步函数。
一开始,我只使用了 sqlAlchemy,并且我在这里尝试了他们的示例。我将这些代码行添加到我的 app/app.py 中,以在服务器启动时创建数据库。一切都很顺利。表 users 是在我的数据库上创建的。
@app.on_event("startup")
async def on_startup():
await create_db_and_tables()
Run Code Online (Sandbox Code Playgroud)
由于我使用的是 SQLModel,因此我将FastAPI Users - SQLModel 的数据库适配器添加到我的虚拟 en 包中。我添加了这些行以便fastapi_users/db/__init__.py能够使用 SQL 模型数据库。
try:
from fastapi_users_db_sqlmodel import ( # noqa: F401
SQLModelBaseOAuthAccount,
SQLModelBaseUserDB,
SQLModelUserDatabase,
)
except ImportError: # pragma: no cover
pass
Run Code Online (Sandbox Code Playgroud)
我还修改了app/users.py, 以SQLModelUserDatabase代替 sqlAchemy 之一。
async def get_user_manager(user_db: SQLModelUserDatabase = Depends(get_user_db)):
yield UserManager(user_db)
Run Code Online (Sandbox Code Playgroud)
以及app/dp.py使用SQLModelUserDatabase,,SQLModelBaseUserDB这里是完整的代码app/db.py
import os
from typing import AsyncGenerator
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from fastapi_users.db import SQLModelUserDatabase, SQLModelBaseUserDB
from sqlmodel import SQLModel
from app.models import UserDB
DATABASE_URL = os.environ.get("DATABASE_URL")
engine = create_async_engine(DATABASE_URL)
async_session_maker = sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False)
async def create_db_and_tables():
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async def get_async_session() -> AsyncSession:
async_session = sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False
)
async with async_session() as session:
yield session
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
yield SQLModelUserDatabase(UserDB, session, SQLModelBaseUserDB)
Run Code Online (Sandbox Code Playgroud)
一旦我运行代码,该表就根本没有创建。我想知道可能是什么问题。我无法理解。任何想法?
By the time I posted this question that was the answer I received from one of the maintainer of fastapi-users that made me switch to sqlAlchemy that time, actually I do not know if they officially released sqlModel DB adapter or not
My guess is that you didn't change the
UserDBmodel so that it inherits from theSQLModelBaseUserDBone. It's necessary in order to letSQLModeldetect all your models and create them.
You can have an idea of what it should look like in
fastapi-users-db-sqlmodeltests: https://github.com/fastapi-users/fastapi-users-db-sqlmodel/blob/3a46b80399f129aa07a834a1b40bf49d08c37be1/tests/conftest.py#L25-L27
请记住,我们并未正式发布此数据库适配器;因为它们存在一些
SQLModel关于UUID(tiangolo/sqlmodel#25)的问题。所以你可能会遇到问题。
这是该问题的 GitHub 链接:https ://github.com/fastapi-users/fastapi-users/discussions/861