繁体   English   中英

FastAPI 图像 POST 和调整大小

[英]FastAPI image POST and resize

我正在使用 FastAPI 创建一个应用程序,该应用程序应该生成已调整大小的上传图像版本。 上传应该通过 POST/images 完成,在调用路径 /images/800x400 后,它应该显示一个 800x400 大小的图像。 这是我到目前为止所拥有的:

from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/images/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.photo.jpg}

(photo.jpg 是与应用文件位于同一位置的图像)

我怎样才能看到这个上传的图像? 当我打电话给http://127.0.0.1:8000/images/我得到: {"detail":"Method Not Allowed"}

如何发布多个图像,然后通过调用 /images/800x400 来调整随机图像的大小以在 800x400 版本中查看它? 我正在考虑使用枕头。 在这种情况下可以吗?

编辑

我现在向前迈进了一步,但在尝试显示图像时仍然出现错误。

from fastapi.responses import FileResponse
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(file)

# example of how you can save the 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]```

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

I would like to use: return FileResponse(some_file_path)
and in the file path put the filename from above. Is it right way of thinking? 

我相信您需要研究HTTP 方法的用途。

邮政

POST 方法用于将实体(您的图像)提交到指定资源,通常会导致 state 发生更改或对服务器产生副作用。

因此,使用 POST 将图像上传到您的后端。

得到

GET 方法请求指定(图像)资源的表示。 使用 GET 的请求应该只检索数据。

使用浏览器导航到站点时,GET 是默认方法。 因此,如果您想在导航到http://127.0.0.1:8000/images/时看到图像,则需要为该端点定义 function(带有 FastAPI 的装饰器)。

了解这些,您可以定义实现目标所需的端点。

编辑

作为参考,这里是上传和保存图像的工作实现。 我使用 Postman 来执行实际请求。

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import FileResponse
import uuid

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(file.filename, "wb") as f:
        f.write(contents)

    return {"filename": file.filename}

这会将使用随机 ID 上传的图像作为文件名保存在应用程序运行的目录中。 当然,您应该使用适当的数据存储,但我认为它应该让您朝着正确的方向前进。

参考

https://www.starlette.io/requests/#request-files

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM