fastapi 模式的额外信息,示例 / Cookie参数 / Header参数
文章目錄
- 1. Pydantic schema_extra
- 2. Field 的附加參數
- 3. Body 額外參數
- 4. Cookie 參數
- 5. Header 參數
- 5.1 重復的 headers
learn from https://fastapi.tiangolo.com/zh/tutorial/schema-extra-example/
添加一個將在文檔中顯示的 example
1. Pydantic schema_extra
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel app = FastAPI()class Item(BaseModel):name: strdescription: Optional[str] = Noneprice: floattax: Optional[float] = Noneclass Config:schema_extra = {"example": {"name": "michael","description": "a learner","price": 100.0, "tax": 0.1}}@app.put("/items/{item_id}") async def update_item(item_id: int, item: Item):res = {"item_id": item_id, "item": item}return res
來看看文檔:http://127.0.0.1:8000/docs#/default/update_item_items__item_id__put
其中: class Config:
schema_extra = {
“example”: {
加黑的字符,大小寫必須完全一致,應該是內置的字段,否則無法顯示例子
2. Field 的附加參數
- Field(None, example=xxx)
3. Body 額外參數
可以通過傳遞額外信息給 Field 同樣的方式操作Path, Query, Body等
from typing import Optional from fastapi import FastAPI, Body from pydantic import BaseModel, Field app = FastAPI()class Item(BaseModel):name: strdescription: Optional[str] = Noneprice: floattax: Optional[float] = None@app.put("/items/{item_id}") async def update_item(item_id: int, item: Item = Body(...,example = { # 加入 example 參數"name": "michael","description": "a learner","price": 100.1, "tax": 0.1}) ):res = {"item_id": item_id, "item": item}return res4. Cookie 參數
聲明 Cookie 參數的結構與聲明 Query 參數和 Path 參數時相同。
第一個值是參數的默認值,同時也可以傳遞所有驗證參數或注釋參數,來校驗參數
你需要使用 Cookie 來聲明 cookie 參數,否則 參數將會被解釋為 查詢參數
from typing import Optional from fastapi import Cookie, FastAPIapp = FastAPI() @app.get("/items/") async def read_items(ads_id: Optional[str] = Cookie(None)):return {"ads_id": ads_id}使用 postman 測試
5. Header 參數
大多數標準的 headers 用 "連字符" 分隔,也稱為 "減號" (-)。
但是像 user-agent 這樣的變量在Python中是無效的。
因此, 默認情況下, Header 將把參數名稱的字符從下劃線 (_) 轉換為連字符 (-) 來提取并記錄 headers
- 如果需要禁用 下劃線到連字符 的自動轉換,設置 Header 的參數 convert_underscores 為 False
- 注意:一些 HTTP 代理和服務器不允許使用帶有下劃線的 headers
- 禁用下劃線自動轉換 strange_header: Optional[str] = Header(None, convert_underscores=False)
5.1 重復的 headers
可以通過一個Python list 的形式獲得 重復header 的 所有值
from typing import Optional, List from fastapi import Cookie, FastAPI, Headerapp = FastAPI() @app.get("/items/") async def read_items(x_token: Optional[List[str]] = Header(None)):return {"x_token value:": x_token}總結
以上是生活随笔為你收集整理的fastapi 模式的额外信息,示例 / Cookie参数 / Header参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 2109. 向字符串添
- 下一篇: LeetCode 1899. 合并若干三