我正在尝试将SQLAlchemy ImageAttach与Pydantic和FastAPI一起使用,但没有取得多大成功。
我以前从未使用过SQLAlchemy ImageAttach,我确信我使用错了。我似乎无法保存任何图像,但我可以让所有非图像方面工作。(我已经成功地集成了SQLAlchemy+Pydantic+FastAPI,还有一些很好的例子可以帮助我。(
我正在尝试制作一个DB支持的网站,用户可以在该网站上创建测验问题,并在问题中嵌入图像。下面的代码突出显示了与测验问题+图像相关的部分。
我的Pydantic模型/模式:
from typing import List, Optional
from pydantic import BaseModel
class QuestionPictureBase(BaseModel):
pass
class QuestionPicture(QuestionPictureBase):
id: int
question_id: int
class Config:
orm_mode = True
class QuestionBase(BaseModel):
header: str
details: str
class QuestionCreate(QuestionBase):
pass
class Question(QuestionBase):
id: int
creator_id: int
pictures: List[QuestionPicture] = []
class Config:
orm_mode = True
SQLAlchemy模型:
from sqlalchemy import create_engine, Boolean, Column, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_imageattach.entity import Image, image_attachment
SQLALCHEMY_DATABASE_URL = "sqlite:///sqlalch.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Question(Base):
__tablename__ = "questions"
id = Column(Integer, primary_key=True, index=True)
header = Column(String, index=True)
details = Column(String, index=True)
creator_id = Column(Integer, ForeignKey("users.id"))
*** pictures = image_attachment("QuestionPicture", uselist=True) ***
creator = relationship("User", back_populates="questions")
class QuestionPicture(Base, Image):
"""Model for pictures associated with the question."""
__tablename__ = "question_pictures"
id = Column(Integer, primary_key=True)
# Not sure if the question ID should also be a unique identifier
# question_id = Column(Integer, ForeignKey("questions.id"), primary_key=True)
question_id = Column(Integer, ForeignKey("questions.id"))
question = relationship("Question", back_populates="pictures")
高亮显示的线
*** pictures = image_attachment("QuestionPicture", uselist=True) ***
就是我认为我做错了什么。但是我不太确定我应该做什么。
我只是不知道image_attachment
函数调用应该如何使用。它似乎只是起了作用;自动地";在SQLAlchemy ImageAttach文档中,我不理解它。
有人有使用SQLAlchemy ImageAttach+Pydantic(+FastAPI(的工作示例吗。最让我困惑的是与皮丹蒂奇的互动。
更新
有人要求提供更多细节,但一个问题实在太多了。因此,我创建了一个git分支,其中包含所有后端,但仅包含后端,称为temp
,并将其推送到公共GitHub repo。
解决方案
下面@r-m-n
的解决方案为我提供了很大的帮助,但我的主要问题是我不清楚我的pictures
数据库需要包含什么。
在查看了一些错误输出并阅读了源代码后,我在这里找到了所需的结构,并调整了我的alembic(数据库版本控制(代码如下:
def upgrade():
op.create_table(
"question_pictures",
sa.Column("id", sa.Integer, primary_key=True, index=True),
sa.Column(
"question_id", sa.Integer, sa.ForeignKey("questions.id"), nullable=False
),
sa.Column("width", sa.Integer, nullable=False),
sa.Column("height", sa.Integer, nullable=False),
#: (:class:`str`) The mimetype of the image
#: e.g. ``'image/jpeg'``, ``'image/png'``.
sa.Column("mimetype", sa.String(255), nullable=False),
sa.Column("original", sa.Boolean, nullable=False, default=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
)
在上面的列表中,缺少width
、height
、original
、mimetype
和created_at
,我不知道我需要添加这些列表。
(上述sa
是sqlalchemy
的缩写,op
是alembic.op
的缩写。(
SQLAlchemy ImageAttach在创建关系时默认使用lazy=dynamic
参数:https://github.com/dahlia/sqlalchemy-imageattach/blob/master/sqlalchemy_imageattach/entity.py#L148.因此question.pictures
返回一个Query
对象而不是列表,您需要调用question.pictures.all()
来获取图片列表。
您可以设置lazy=select
或lazy=joined
。请在此处查看有关懒惰参数的更多信息。
pictures = image_attachment("QuestionPicture", uselist=True, lazy='select')