Cookie 變量
從 fastapi 引入 Cookie 后,可以使用類似 Query应民、Path 的方式來獲取 cookie 的值话原,例如:
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}
頭部變量(Header Parameters)
從 fastapi 中引入 Header 后,就可以用類似 Query诲锹、Cookie 的方式來獲取頭部變量的值繁仁,例如:
from typing import Optional
from fastapi import FastAPI, Header
app = FastAPI()
@app.get("/items/")
async def read_items(user_agent: Optional[str] = Header(None)):
return {"User-Agent": user_agent}
自動轉(zhuǎn)換
頭部變量的變量名與 http 頭部的變量名之間會經(jīng)過一個轉(zhuǎn)換過程,把變量名轉(zhuǎn)變?yōu)樾懝樵埃覚M線 - 轉(zhuǎn)換為下劃線 _ 黄虱,比如頭部是 User-Agent ,轉(zhuǎn)換后就是 user_agent 庸诱。這是因為在Python中變量名不能用橫線捻浦。
重復(fù)的頭變量
如果我們在請求頭里對一個變量設(shè)置了多個值晤揣,那么 fastapi 會把這些值都取出來存入一個 List 中。
響應(yīng)模型(Responce Model)
響應(yīng)模型是可以用來控制響應(yīng)體中的數(shù)據(jù)朱灿,按照一定方式組織后返回的操作方法昧识。比如我們可以對數(shù)據(jù)進(jìn)行過濾、
使用響應(yīng)模型母剥,需要在路由函數(shù)中指定 response_model 對應(yīng)的類滞诺,然后使用 response_model_include 或 response_model_exclude 來指定要包含的字段或要排除的字段。例如:
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: float = 10.5
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz",
"description": "There goes my baz",
"price": 50.2,
"tax": 10.5,
},
}
@app.get(
"/items/{item_id}/name",
response_model=Item, # 指定響應(yīng)模型
response_model_include=["name", "description"], # 選取要返回的字段
)
async def read_item_name(item_id: str):
return items[item_id]
@app.get(
"/items/{item_id}/public",
response_model=Item,
response_model_exclude=["tax"] # 選取要排除的字段
)
async def read_item_public_data(item_id: str):
return items[item_id]
接下來可以訪問 http://localhost:8000/items/baz/public 以及http://localhost:8000/items/baz/name查看結(jié)果环疼。
在路由方法中习霹,我們還可以設(shè)置 response_model_exclude_unset=True ,這樣就只會返回非空的那些字段炫隶。
多個Model
我們的 Model 之間還可以有繼承關(guān)系淋叶,這樣可以減少重復(fù),例如:
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
import hashlib
app = FastAPI()
class UserBase(BaseModel):
username: str
email: str
full_name: Optional[str] = None
class UserIn(UserBase):
password: str
class UserInDB(UserBase):
hashed_password: str
def fake_save_user(user_in: UserIn):
salted_password = 'mysalt' + user_in.password
hashed_password = hashlib.md5(salted_password.encode(encoding="UTF-8")).hexdigest()
user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
print("User saved! ..not really")
return user_in_db
@app.post("/user/", response_model=UserInDB)
async def create_user(user_in: UserIn):
user_saved = fake_save_user(user_in)
return user_saved
響應(yīng)模型為列表
我們得響應(yīng)模型還可以是列表格式伪阶,例如:
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str
items = [
{"name": "Foo", "description": "There comes my hero"},
{"name": "Red", "description": "It's my aeroplane"},
]
@app.get("/items/", response_model=List[Item]) # Item 的列表
async def read_items():
return items
響應(yīng)模型為任意的字典類型
響應(yīng)模型還可以是 typing 中引入的 Dict 類型煞檩,例如:
from typing import Dict
from fastapi import FastAPI
app = FastAPI()
@app.get("/keyword-weights/", response_model=Dict[str, float])
async def read_keyword_weights():
return {"foo": 2.3, "bar": 3.4}
響應(yīng)狀態(tài)碼
在裝飾器中可以使用 status_code 參數(shù)來指定響應(yīng)的狀態(tài)碼,可以使用整數(shù)如 200栅贴,404等斟湃,也可以從 fastapi 中引入 status 后使用常量,例如:
from fastapi import FastAPI
app = FastAPI()
@app.post("/items/", status_code=201)
async def create_item(name: str):
return {"name": name}
@app.get("/errors/", status_code=404)
async def errors():
return {"name": "404 HTTP Not Found"}
值得注意的是檐薯,即便是404錯誤凝赛,JSON的數(shù)據(jù)依然會被返回,這樣是為了前后端分離考慮的坛缕。