如何使用FastApi将多个图像URL添加到Postgres数据库中?
使用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:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要加入前循环中的URL。
首先制作一个空数组来存储文件URL,然后在for循环中附加。然后最终使用加入将字符串与逗号连接在一起,为您提供带有逗号分隔的项目的字符串
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
首先,您需要更改数据库模型:
注意:不要忘记生成和应用迁移。
然后只需将
imgs_url
作为列表
传递给product
initializer:最后,您可以更改模型工厂:
我认为您应该重新考虑您的设计并进行采取恕我直言,更好的方法,与桌子关系。因此,您将创建两个表:
products
(如已经定义)和images
(新一张)将通过外键连接:At first, you need to alter your db model:
Note: do not forget to generate and apply migration.
then simply pass
imgs_url
as alist
toProduct
initializer:Finally, you can alter your model factory:
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) andimages
(new one) which will be connected via foreign key: