- FastAPI 教程
- FastAPI - 首頁
- FastAPI - 簡介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 型別提示
- FastAPI - IDE 支援
- FastAPI - REST 架構
- FastAPI - 路徑引數
- FastAPI - 查詢引數
- FastAPI - 引數驗證
- FastAPI - Pydantic
- FastAPI - 請求體
- FastAPI - 模板
- FastAPI - 靜態檔案
- FastAPI - HTML 表單模板
- FastAPI - 訪問表單資料
- FastAPI - 上傳檔案
- FastAPI - Cookie 引數
- FastAPI - 頭部引數
- FastAPI - 響應模型
- FastAPI - 巢狀模型
- FastAPI - 依賴項
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 資料庫
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - WebSockets
- FastAPI - FastAPI 事件處理器
- FastAPI - 掛載子應用
- FastAPI - 中介軟體
- FastAPI - 掛載 Flask 應用
- FastAPI - 部署
- FastAPI 有用資源
- FastAPI - 快速指南
- FastAPI - 有用資源
- FastAPI - 討論
FastAPI - Cookie 引數
Cookie 是 HTTP 頭部之一。Web 伺服器向客戶端傳送響應時,除了請求的資料外,還會插入一個或多個 Cookie。Cookie 是儲存在客戶端機器上的一小部分資料。在來自同一客戶端的後續連線請求中,此 Cookie 資料也會與 HTTP 請求一起附加。
Cookie 用於記錄有關客戶端瀏覽的資訊。Cookie 是一種可靠的方法,可以在 HTTP 協議的無狀態通訊中檢索有狀態資訊。
在 FastAPI 中,可以使用set_cookie() 方法在響應物件上設定 Cookie 引數。
response.set_cookie(key, value)
示例
這是一個set_cookie() 方法的示例。我們有一個名為 content 的 JSON 響應物件。在其上呼叫set_cookie() 方法以設定 Cookie 為key="usrname" 和value="admin" -
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.post("/cookie/")
def create_cookie():
content = {"message": "cookie set"}
response = JSONResponse(content=content)
response.set_cookie(key="username", value="admin")
return response
要在後續訪問中讀取 Cookie,請在 FastAPI 庫中使用 Cookie 物件。
from fastapi import FastAPI, Cookie
app = FastAPI()
@app.get("/readcookie/")
async def read_cookie(username: str = Cookie(None)):
return {"username": username}
在 Swagger API 中檢查這兩個端點。這兩個路由為"/cookies" 和"/readcookie"。執行繫結到 "/cookies" 的create_cookie() 函式。響應只是內容,儘管已設定了 Cookie。
當執行read_cookie() 函式時,Cookie 會被讀回並顯示為響應。此外,請注意文件將使用者名稱識別為 Cookie 引數。
廣告