FastAPI請求系列(四) Request Cookie/Header/Form/File


一、Cookie

Cookie的定義與聲明與Query和Path類似:

from typing import Optional
from fastapi import Cookie, FastAPI

app = FastAPI()


@app.get("/items/")
async def read_items(ads_id: Optional[str] = Cookie(None)):
    return {"ads_id": ads_id}

此處需要使用Cookie來進行聲明,否則將會被解析為查詢參數。那么這樣應該如何進行測試呢?此處可以使用postman進行測試:

注意在Headers中key是Cookie,否則將會被解析為Header參數。

二、Header

 Header與之前的Cookie使用一樣:

from typing import Optional, List
from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(user_agent: Optional[str] = Header(None, convert_underscores=True), x_token: List[str] = Header(None)):
    return {"User-Agent": user_agent, "x_token": x_token}

需要使用Header來進行聲明,否則就會將其作為查詢參數。

  • convert_underscores 是為了解決有些HTTP代理和服務器是不允許在請求頭中帶有下划線的,所以Header提供convert_underscores屬性讓設置,默認是True,也就是FastAPI會自動轉換
  • x_token 請求頭參數可以接受多個值,以列表的形式接收,其表現形式如下。

三、表單數據

   上述接受的請求數據是json類型的,當需要接受並且處理表單數據時使用Form,不過在使用時注意是否已經安裝python-multipart第三方包,如果沒有安裝,可以通過pip安裝:

pip install python-multipart

  比如,在登錄時提交用戶名和密碼的表單數據到后台進行驗證,FastAPI對於表單Form的使用與Body/Query/Path/Cookie相同。

from fastapi import FastAPI, Form

app = FastAPI()


@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username}

這樣在api中使用時顯然media-type與之前application/json不同:

四、文件上傳

在進行文件上傳之前,需要確定是否已經安裝python-multipart第三方包,如果沒有安裝,可以通過pip安裝:

pip install python-multipart

因為上傳的文件是以“form data”的形式向后台發送的。

1、小文件上傳

  • 單個文件上傳
from fastapi import FastAPI, File


app = FastAPI()


@app.post("/file/")
async def create_file(file: bytes = File(...)):return {"file_size": len(file)}

  通過File來進行聲明,這樣file參數就不會被當作查詢參數或者請求體參數。在路徑操作函數中聲明bytes類型,這樣接收的就是bytes類型,並且寫入到內存,所以適合於小文件上傳。

  • 多個文件上傳

多個文件上傳就是bytes類型定義為List[bytes]即可:

from typing import List
from fastapi import FastAPI, File

app = FastAPI()


@app.post("/multi/file/")
async def create_multi_file(file: List[bytes] = File(...)):
    return {"file_size": len(file)}

如圖所示:

 2、大文件上傳

  • 單個文件上傳
from fastapi import FastAPI, File, UploadFile

app = FastAPI()


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

使用UploadFile的優勢:

(1)文件存儲在內存中,使用的內存達到閾值后,將被保存在磁盤中

(2)適合於圖片、視頻大文件

(3)可以獲取上傳的文件的元數據,如文件名,創建時間等

(4)有文件對象的異步接口上傳的文件是Python文件對象,可以使用write(), read(), seek(), close()操作

  • 多個文件上傳
from typing import List
from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/multi/uploaadfile/")
async def create_multi_upload_file(files: List[UploadFile] = File(...)):
    results = []
    for file in files:
        content = await file.read()
        print(content)
        results.append({"filename": file.filename, "content_type": file.content_type})
    return results

上面讀取每個文件的內容,通過異步的方式完成。調用接口如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM