gpt4 book ai didi

python - 快速 API - 如何在 GET 中显示来自 POST 的图像?

转载 作者:行者123 更新时间:2023-12-05 01:08:15 25 4
gpt4 key购买 nike

我正在使用 FastAPI 创建一个应用程序,该应用程序应该生成已上传图像的调整大小版本。上传应该通过 POST/images 完成,在调用路径/images/800x400 后,它应该显示来自数据库的随机图像,大小为 800x400。我在尝试显示图像时遇到错误。

 from fastapi.responses import FileResponse
import uuid

app = FastAPI()

db = []

@app.post("/images/")
async def create_upload_file(file: UploadFile = File(...)):

contents = await file.read()

db.append(file)

with open(file.filename, "wb") as f:
f.write(contents)

return {"filename": file.filename}

@app.get("/images/")
async def show_image():
return db[0]

作为回应,我得到:

{
"filename": "70188bdc-923c-4bd3-be15-8e71966cab31.jpg",
"content_type": "image/jpeg",
"file": {}
}

我想使用:return FileResponse(some_file_path)并在文件路径中放置上面的文件名。这是正确的思维方式吗?

最佳答案

首先,您将 File 对象添加到您的数据库列表中,这解释了您得到的响应。

您想将文件的内容写入您的数据库。

如果您将其用作“持久性”,您也不需要将其写入文件系统(当然,如果您关闭或重新加载应用程序,所有文件都会消失)。

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import Response
import os
from random import randint
import uuid

app = FastAPI()

db = []


@app.post("/images/")
async def create_upload_file(file: UploadFile = File(...)):

file.filename = f"{uuid.uuid4()}.jpg"
contents = await file.read() # <-- Important!

db.append(contents)

return {"filename": file.filename}


@app.get("/images/")
async def read_random_file():

# get a random file from the image db
random_index = randint(0, len(db) - 1)

# return a response object directly as FileResponse expects a file-like object
# and StreamingResponse expects an iterator/generator
response = Response(content=db[random_index])

return response

如果您想将文件实际保存到磁盘,这是我会使用的方法(对于完整的应用程序,仍然首选真正的数据库)

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import FileResponse
import os
from random import randint
import uuid

IMAGEDIR = "fastapi-images/"

app = FastAPI()


@app.post("/images/")
async def create_upload_file(file: UploadFile = File(...)):

file.filename = f"{uuid.uuid4()}.jpg"
contents = await file.read() # <-- Important!

# example of how you can save the file
with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
f.write(contents)

return {"filename": file.filename}


@app.get("/images/")
async def read_random_file():

# get a random file from the image directory
files = os.listdir(IMAGEDIR)
random_index = randint(0, len(files) - 1)

path = f"{IMAGEDIR}{files[random_index]}"

# notice you can use FileResponse now because it expects a path
return FileResponse(path)

引用:

(FastAPI 继承了 Starlette 的响应)

(Tiangolo的文档还是很不错的)

关于python - 快速 API - 如何在 GET 中显示来自 POST 的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66178227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com