快速API-如何在GET中显示POST中的图像? [英] Fast API - how to show an image from POST in GET?
本文介绍了快速API-如何在GET中显示POST中的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用FastAPI创建一个应用程序,该应用程序应该生成已上传图像的调整大小版本。上传应该通过POST/IMAIES完成,在调用路径/IMAIES/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)
并在文件路径中放入上面的文件名。这是正确的思维方式吗?
推荐答案
首先,您要将文件对象添加到数据库列表中,这解释了您获得的响应。
您要将文件的内容写入数据库。
如果您将其用作您的持久性文件系统(当然,如果您关闭或重新加载您的应用程序,所有文件都将消失),您也不需要将其写入文件系统。
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的文档仍然非常好用)
这篇关于快速API-如何在GET中显示POST中的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文