如何使用FastApi将多个图像URL添加到Postgres数据库中?

发布于 2025-02-06 12:39:21 字数 1877 浏览 2 评论 0原文

使用FastAPI多个上传函数,我正在尝试将图像上传到我的服务器,并将URL作为列表保存到我的Postgres数据库。 这是我用来上传图像的代码:

@router.post('/addProductFD', status_code=status.HTTP_201_CREATED, response_model=ShowProduct)
async def create(
    name: str = Form(...),
    price: float = Form(...),
    description: str = Form(...),
    files: List[UploadFile] = File(...),
    db: Session = Depends(get_db),
):
    for file in files:
        try:
            FILEPATH = "./static/product_images/"
            pimage_name = FILEPATH + imghex(file.filename)
            contents = await file.read()
            with open(pimage_name, 'wb') as f:
                f.write(contents)
        except Exception:
            return {"message": "There was an error uploading the file(s)"}
        finally:
            await file.close()
    file_urls = "localhost:8000" + pimage_name[1:]

    new_item = Product(
        name=name,
        price=price,
        description=description,
        imgs_url=file_urls,
    )

    db.add(new_item)
    db.commit()
    db.refresh(new_item)
    {"filenames": [file.filename for file in files]}
    return new_item

运行此代码时,它将图像上传并将第一个图像的URL添加到我的数据库中。请如何制作此代码以将图像URL添加到我的数据库中。 这是我想做的示例:

下面是schemas.showproduct:

class ShowProduct(ProductBase):
    name: str
    description: str
    img: str

    class Config():
        orm_mode = True

下面是我的postgresdb models.product.product:

class Product(Base):
    name = Column(String, nullable=False)
    description = Column(Text, nullable=False)
    owner = relationship("Vendor", back_populates="product")
    img = Column(String)

所以我想收到imageUrls的列表,然后将其添加到 img 数据库列:

请帮助!

Using the fastAPI multiple uploads function, i am trying to upload images to my server and save the urls as a list to my postgres database.
Here is the code i am using to upload the image:

@router.post('/addProductFD', status_code=status.HTTP_201_CREATED, response_model=ShowProduct)
async def create(
    name: str = Form(...),
    price: float = Form(...),
    description: str = Form(...),
    files: List[UploadFile] = File(...),
    db: Session = Depends(get_db),
):
    for file in files:
        try:
            FILEPATH = "./static/product_images/"
            pimage_name = FILEPATH + imghex(file.filename)
            contents = await file.read()
            with open(pimage_name, 'wb') as f:
                f.write(contents)
        except Exception:
            return {"message": "There was an error uploading the file(s)"}
        finally:
            await file.close()
    file_urls = "localhost:8000" + pimage_name[1:]

    new_item = Product(
        name=name,
        price=price,
        description=description,
        imgs_url=file_urls,
    )

    db.add(new_item)
    db.commit()
    db.refresh(new_item)
    {"filenames": [file.filename for file in files]}
    return new_item

When i run this code, it uploads the images and adds the url of just the first image to my database. Please how do i make this code to add the image urls to my database as a list.
Here is an example of what i want to do:
enter image description here

Below is the schemas.ShowProduct:

class ShowProduct(ProductBase):
    name: str
    description: str
    img: str

    class Config():
        orm_mode = True

Below is my postgresDB models.product:

class Product(Base):
    name = Column(String, nullable=False)
    description = Column(Text, nullable=False)
    owner = relationship("Vendor", back_populates="product")
    img = Column(String)

So i want to recieve a list of the imageurls and add it to the img database column:

Please help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

颜漓半夏 2025-02-13 12:39:22

您需要加入前循环中的URL。

首先制作一个空数组来存储文件URL,然后在for循环中附加。然后最终使用加入将字符串与逗号连接在一起,为您提供带有逗号分隔的项目的字符串

fileList = []
for file in files:
        try:
            FILEPATH = "./static/product_images/"
            pimage_name = FILEPATH + imghex(file.filename)
            contents = await file.read()
            with open(pimage_name, 'wb') as f:
                f.write(contents)
        except Exception:
            return {"message": "There was an error uploading the file(s)"}
        finally:
            await file.close()
        fileList.append("localhost:8000" + pimage_name[1:])

    file_urls = ",".join(fileList)

You need to join the urls in the for-loop.

first make an empty array to store the file urls, then in the for loop append to it. Then finally use join to concatenate the strings with commas to give you a string with comma separated items

fileList = []
for file in files:
        try:
            FILEPATH = "./static/product_images/"
            pimage_name = FILEPATH + imghex(file.filename)
            contents = await file.read()
            with open(pimage_name, 'wb') as f:
                f.write(contents)
        except Exception:
            return {"message": "There was an error uploading the file(s)"}
        finally:
            await file.close()
        fileList.append("localhost:8000" + pimage_name[1:])

    file_urls = ",".join(fileList)

不喜欢何必死缠烂打 2025-02-13 12:39:21

首先,您需要更改数据库模型:

class Product(Base):
    name = Column(String, nullable=False)
    description = Column(Text, nullable=False)
    owner = relationship("Vendor", back_populates="product")
    imgs_url = Column(ARRAY(String))

注意:不要忘记生成和应用迁移。

然后只需将imgs_url作为列表传递给product initializer:

new_item = Product(
        name=name,
        price=price,
        description=description,
        imgs_url=["url1", "url2"],
    )

最后,您可以更改模型工厂:

class ShowProduct(ProductBase):
    name: str
    description: str
    imgs_url: list[str]

    class Config:
        orm_mode = True

我认为您应该重新考虑您的设计并进行采取恕我直言,更好的方法,与桌子关系。因此,您将创建两个表:products(如已经定义)和images(新一张)将通过外键连接:

class Product(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    description = Column(Text, nullable=False)
    owner = relationship("Vendor", back_populates="product")
    images = relationship("Image", back_populates="product")
class Image(Base):
    url = Column(String, nullable=False)
    product_id = Column(Integer, ForeignKey("product.id"))
    product = relationship("Product", back_populates="images")

At first, you need to alter your db model:

class Product(Base):
    name = Column(String, nullable=False)
    description = Column(Text, nullable=False)
    owner = relationship("Vendor", back_populates="product")
    imgs_url = Column(ARRAY(String))

Note: do not forget to generate and apply migration.

then simply pass imgs_url as a list to Product initializer:

new_item = Product(
        name=name,
        price=price,
        description=description,
        imgs_url=["url1", "url2"],
    )

Finally, you can alter your model factory:

class ShowProduct(ProductBase):
    name: str
    description: str
    imgs_url: list[str]

    class Config:
        orm_mode = True

I think you should rethink your design and take imho better approach, with table relationships. So you would create two tables: products (as already defined) and images (new one) which will be connected via foreign key:

class Product(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    description = Column(Text, nullable=False)
    owner = relationship("Vendor", back_populates="product")
    images = relationship("Image", back_populates="product")
class Image(Base):
    url = Column(String, nullable=False)
    product_id = Column(Integer, ForeignKey("product.id"))
    product = relationship("Product", back_populates="images")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文