繁体   English   中英

SQLAlchemy 型号与 Pydantic 型号

[英]SQLAlchemy models vs Pydantic models

我正在关注本教程以使其适应我的需求,在这种情况下,执行 sql 模块,我需要在其中记录 Webhook 从 gitlab 问题收集的数据。

对于数据库模块,我使用SQLAlchemy库和PostgreSQL作为数据库引擎。

所以,我想解决一些疑问,我对Pydantic库的使用有疑问,特别是这个例子

根据我的阅读,Pydantic 是一个库,用于使用具有属性的类进行数据验证。

但是有些东西我不是很明白……Pydantic的整合是绝对必要的吗? 使用 Pydantic 的目的我了解,但是将 Pydantic 与 SQLAlchemy 模型的集成我不明白。

在教程中, models.py有以下内容:

from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from .database import Base


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)

    items = relationship("Item", back_populates="owner")


class Item(Base):
    __tablename__ = "items"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    description = Column(String, index=True)
    owner_id = Column(Integer, ForeignKey("users.id"))

    owner = relationship("User", back_populates="items")

并且schemas.py有以下内容:

from typing import Optional

from pydantic import BaseModel


class ItemBase(BaseModel):
    title: str
    description: Optional[str] = None


class ItemCreate(ItemBase):
    pass


class Item(ItemBase):
    id: int
    owner_id: int

    class Config:
        orm_mode = True


class UserBase(BaseModel):
    email: str


class UserCreate(UserBase):
    password: str


class User(UserBase):
    id: int
    is_active: bool
    items: list[Item] = []

    class Config:
        orm_mode = True

我知道在 Pydantic 中定义对象的主要方法是通过模型,而且我知道模型只是从BaseModel继承的类。

为什么会创建ItemBase、ItemCreateItemBase继承自ItemBase?

ItemBase 中,它传递了 Item 表中严格必需的字段? 并定义它的类型?

ItemCreate class 我已经看到它在crud.py中用于创建用户,在我的情况下,我必须对事件做同样的事情? 我的意思是,我必须创建一个这样的类:

class IssueCreate(BaseModel):
    pass

我的示例尝试遵循相同的工作流程:

models.py

import sqlalchemy

from sqlalchemy import Column, Table
from sqlalchemy import Integer, String, Datetime, TIMESTAMP

from .database import Base


class Issues(Base):
    __tablename__ = 'issues'

    id = Column(Integer, primary_key=True)
    gl_assignee_id = Column(Integer, nullable=True)
    gl_id_user = Column(Integer, nullable=False)
    current_title = Column(String, nullable=False)
    previous_title = Column(String, nullable=True)
    created_at = Column(TIMESTAMP(timezone=False), nullable=False)
    updated_at = Column(TIMESTAMP(timezone=False), nullable=True)
    closed_at = Column(TIMESTAMP(timezone=False), nullable=True)
    action = Column(String, nullable=False)

schemas.py

from pydantic import BaseModel

class IssueBase(BaseModel):
    updated_at: None
    closed_at: None
    previous_title: None

class Issue(IssueBase):
    id: int
    gl_task_id: int
    gl_assignee_id: int
    gl_id_user: int
    current_title: str
    action: str

    class Config:
        orm_mode = True

但我不知道我这样做是否正确,欢迎提出任何建议。

您提到的教程是关于 FastAPI 的。 Pydantic 本身与 SQL、SQLAlchemy 或关系数据库无关。 FastAPI 向您展示了一种使用关系数据库的方法。


[使用 FastAPI 时] 是否需要集成 pydantic?

是的。 根据文档,Pydantic 是一项要求:

要求

Python 3.6+

FastAPI 站在巨人的肩膀上:

  • 用于web零件的 Starlette。
  • Pydantic用于数据部分。

为什么会创建ItemBase、ItemCreate和ItemBase继承自ItemBase?

Pydantic 模型是 FastAPI 用来定义其接收(请求)和返回(响应)的数据模式的方式。 ItemCreate表示创建项目所需的数据。 Item表示查询项目时返回的数据。 ItemCreateItem共有的字段放在ItemBase中以避免重复。


在 ItemBase 中,它传递了 Item 表中严格必需的字段? 并定义它的类型?

ItemBase具有ItemCreateItem共有的字段。 它与表无关。 这只是一种避免重复的方法。 pydantic model 的每个字段都必须有一个类型,那里没有什么不寻常的。


在我的情况下,我必须对这些事件做同样的事情?

如果您有类似的场景,其中您接收的数据(请求)和返回的数据(响应)具有公共字段(相同的名称和类型),您可以使用这些字段定义 model 并让其他模型继承从中避免重复。


这可能是理解 FastAPI 和 pydantic 的一种(可能是简单化的)方式:

FastAPI 将请求转换为 pydantic 模型。 这些 pydantic 模型是您的输入数据,也称为模式(可能是为了避免与模型一词的其他用途混淆)。 你可以对这些模式做任何你想做的事情,包括使用它们来创建关系数据库模型和持久化它们。

无论您想作为响应返回什么数据,FastAPI 都需要将其转换为 pydantic model(模式)。 恰好 pydantic 支持一个orm_mode选项,该选项允许它解析具有属性而不是字典的任意对象。 使用该选项,您可以返回关系数据库 model,FastAPI 会将其转换为相应的模式(使用 pydantic)。

FastAPI 使用了 pydantic 的解析和验证特性,但是你必须遵循一个简单的规则:你接收到的数据必须符合输入模式,你想要返回的数据必须符合 output 模式。 您负责决定两者之间的任何传递。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM