代码之家  ›  专栏  ›  技术社区  ›  Oskar Watsfeldt

由于异步SQLAlchemy,FastAPI用户路由与关系失败

  •  0
  • Oskar Watsfeldt  · 技术社区  · 1 年前

    我开始使用FastAPI用户库作为FastAPI后端。该库包括一些注册和获取用户的路由,但一旦我将关系放在用户模型上,这些路由就不起作用。

    我有一个用户,应该有很多帖子。如果我将UserRead Pydantic模型/架构定义为包含posts,那么FastAPI将尝试为响应加载posts。这失败了,因为FastAPI用户使用异步SQLAlchemy,它不能延迟加载(没有隐式IO)。具体来说,我打电话给 /auth/register 当遵循时 docs .

    以下是我的SQLAlchemy模型:

    class Mixin(MappedAsDataclass, SQLAlchemyBaseUserTable[int]):
        pass
    
    class User_DB(BaseModel_DB, Mixin):
        __tablename__ = "user_table"
        id: Mapped[int] = mapped_column(primary_key=True, init=False)  # type: ignore . It's fine
        firstname: Mapped[str] = mapped_column()
        posts: Mapped[list["Post_DB"]] = relationship(init=False)
    
    class Post_DB(BaseModel_DB):
        __tablename__ = "post_table"
    
        id: Mapped[int] = mapped_column(primary_key=True, init=False)
        name: Mapped[str] = mapped_column()
        user_id: Mapped[int] = mapped_column(ForeignKey("user_table.id"))
    

    和UserRead架构:

    class UserRead(fastapi_users_schemas.BaseUser[int], BaseSchema):
        firstname: str
        email: str
        posts: list[PostRead]  # uncommenting this makes the route work
    

    调用POST时会引发以下问题 /身份验证/注册 数据。此错误来自异步SQLAlchemy加载,然后该加载尝试延迟访问未急切加载的属性。因此,将帖子排除在UserRead之外,框架不会尝试加载它。

    Error extracting attribute: MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place?

    因此,一种可能性可能是为上的每个关系指定热切负载 User_DB 但是,如果这是建立关系的唯一途径,为什么FastAPI用户的文档不这么说呢?它还迫使我们对每一个我们想要返回的关系属性进行热切的加载。

    问: 如何与FastAPI用户使用关系?

    包含的路线甚至不能与简单的相关模型一起使用。用此复制 minimal repo I made .

    0 回复  |  直到 1 年前