我处理 FastAPI 并且无法弄清楚如何简化(从我对 django 的经验的角度来看)事情 - 将带有图像的产品添加到数据库中。据我了解,图像应该存储在静态文件夹中,并且只有指向它的链接应该存储在数据库中。根据官方文档的信息,我添加了这个方案
架构.py
from pydantic import BaseModel, HttpUrl
from typing import Optional
class ProductImageSchema(BaseModel):
url: HttpUrl
name: str
class ProductSchema(BaseModel):
name: str
description: Optional[str] = None
image: Optional[ProductImage] = None
我正在使用 SQLAlchemy。现在我的第一个问题是如何正确描述产品模型。 模型.py
product = Product(
"product",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(50)),
Column("description", String(50)),
Column(....str_or_url..????) # field with relation with image,
)
并且不清楚如何创建产品对象的新实例。就像是...
crud.py
async def post(payload: ProductSchema, file: UploadFile = File(...)):
content = await file.read()
if file.content_type not in ['image/jpeg', 'image/png']:
raise HTTPException(status_code=406, detail="Only .jpeg or .png files allowed")
file_name = f'{uuid.uuid4().hex}{ext}'
async with aiofiles.open(file_name, "wb") as f:
await f.write(content)
query = product.insert().values(title=payload.name, description=payload.description, image=????????)
return await database.execute(query=query)