簡體   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