FastAPI請求系列(四) Request CookieHeaderFormFile

一、Cookie

Cookie的定義與宣告與Query和Path類似:

from typing import Optionalfrom fastapi import Cookie, FastAPIapp = FastAPI()@app。get(“/items/”)async def read_items(ads_id: Optional[str] = Cookie(None)):    return {“ads_id”: ads_id}

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

FastAPI請求系列(四) Request CookieHeaderFormFile

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

二、Header

Header與之前的Cookie使用一樣:

from typing import Optional, Listfrom fastapi import FastAPI, Headerapp = 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 請求頭引數可以接受多個值,以列表的形式接收,其表現形式如下

FastAPI請求系列(四) Request CookieHeaderFormFile

三、表單資料

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

pip install python-multipart

比如,在登入時提交使用者名稱和密碼的表單資料到後臺進行驗證,FastAPI對於表單Form的使用與Body/Query/Path/Cookie相同。

from fastapi import FastAPI, Formapp = FastAPI()@app。post(“/login/”)async def login(username: str = Form(。。。), password: str = Form(。。。)):    return {“username”: username}

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

FastAPI請求系列(四) Request CookieHeaderFormFile

四、檔案上傳

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

pip install python-multipart

因為上傳的檔案是以“form data”的形式向後臺傳送的。

1。 小檔案上傳

單個檔案上傳

from fastapi import FastAPI, Fileapp = 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 Listfrom fastapi import FastAPI, Fileapp = FastAPI()@app。post(“/multi/file/”)async def create_multi_file(file: List[bytes] = File(。。。)):    return {“file_size”: len(file)}

如圖所示:

FastAPI請求系列(四) Request CookieHeaderFormFile

2。 大檔案上傳

單個檔案上傳

from fastapi import FastAPI, File, UploadFileapp = 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 Listfrom fastapi import FastAPI, File, UploadFileapp = 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