我正在使用 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]
Run Code Online (Sandbox Code Playgroud)
作为回应我得到:
{
"filename": "70188bdc-923c-4bd3-be15-8e71966cab31.jpg",
"content_type": "image/jpeg",
"file": {}
}
Run Code Online (Sandbox Code Playgroud)
我想使用: return FileResponse(some_file_path) 并在文件路径中输入上面的文件名。这是正确的思维方式吗?
im_*_*aby 10
首先,您将 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
Run Code Online (Sandbox Code Playgroud)
如果您想实际将文件保存到磁盘,这是我会使用的方法(对于完整的应用程序来说,真正的数据库仍然是首选)
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)
Run Code Online (Sandbox Code Playgroud)
(FastAPI 继承了 Starlette 的响应)
(Tiangolo的文档还是非常好拥有的)
| 归档时间: |
|
| 查看次数: |
18900 次 |
| 最近记录: |