快速API -如何显示从POST在GET图像?



我正在使用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": {}
}

我想使用:返回filerresponse (some_file_path)在文件路径中放入上面的文件名。这种思维方式对吗?

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

您想要将文件的内容写入您的db。

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

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的响应)

<<ul>
  • Starlette响应/gh>
  • Starlette StreamingResponse
  • Starlette FileResponse
  • (Tiangolo的文档仍然很好)

    <<ul>
  • FastAPI响应/gh>
  • FastAPI StreamingResponse
  • FastAPI FileResponse
  • 最新更新