I deal with FastAPI and can't figure out how to make simple (from the point of view of my experience with django) thing - add a product with an image to the database. As I understood it, the image should be stored in a static folder and only a link to it should be stored in the database. Based on the information from the official documentation, I have added this scheme
schema.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
I'm using SQLAlchemy. Now the first question I have is how to properly describe the product model. models.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,
)
And it is not clear how to create new instances of the product object. Something like...
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)