日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

fastapi 响应模型 / 响应状态码 / 表单参数

發(fā)布時間:2024/7/5 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 fastapi 响应模型 / 响应状态码 / 表单参数 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 1. response_model
    • 2. 添加輸出模型
    • 3. 響應(yīng)模型編碼參數(shù)
    • 4. response_model_include 和 response_model_exclude
    • 5. 代碼復(fù)用:繼承
    • 6. Union
    • 7. 任意 dict 的響應(yīng)
    • 8. 響應(yīng)狀態(tài)碼
    • 9. 表單參數(shù)

learn from https://fastapi.tiangolo.com/zh/tutorial/response-model/

1. response_model

響應(yīng)模型 不是 路徑參數(shù)

from typing import Optional, List from fastapi import Cookie, FastAPI, Header from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Optional[str] = Noneprice: floattax: Optional[float] = Nonetags: List[str] = []@app.post("/items/", response_model=Item) # 裝飾器方法的一個參數(shù) async def create_items(item: Item):return item

or

@app.post("/items/", response_model=List[Item]) # 裝飾器方法的一個參數(shù) async def create_items(item: Item):return [item, item]

響應(yīng)模型 對 返回的數(shù)據(jù) 進(jìn)行轉(zhuǎn)換,校驗(yàn)

例如:

from typing import Optional, List from fastapi import Cookie, FastAPI, Header from pydantic import BaseModel, EmailStrapp = FastAPI()class UserIn(BaseModel):username: strpassword: stremail: EmailStrfull_name: Optional[str] = None@app.post("/user/", response_model=UserIn) # 裝飾器方法的一個參數(shù) async def create_user(user: UserIn):return user

永遠(yuǎn)不要 存儲用戶的 明文密碼,也不要在響應(yīng)中 發(fā)送密碼。

2. 添加輸出模型

  • 輸出的時候不給密碼,更改響應(yīng)模型為不帶密碼的
from typing import Optional, List from fastapi import Cookie, FastAPI, Header from pydantic import BaseModel, EmailStrapp = FastAPI()class UserIn(BaseModel):username: strpassword: stremail: EmailStrfull_name: Optional[str] = Noneclass UserOut(BaseModel):username: stremail: EmailStrfull_name: Optional[str] = None@app.post("/user/", response_model=UserOut) # 裝飾器方法的一個參數(shù) async def create_user(user: UserIn):return user


3. 響應(yīng)模型編碼參數(shù)

  • response_model_exclude_unset 參數(shù) True,輸出忽略 未明確設(shè)置的 字段
  • response_model_exclude_defaults=True,忽略跟默認(rèn)值一樣的字段
  • response_model_exclude_none=True,忽略 None 的字段
from typing import Optional, List from fastapi import Cookie, FastAPI, Header from pydantic import BaseModel, EmailStrapp = FastAPI()class Item(BaseModel):name: strdescription: Optional[str] = Noneprice: floattax: float = 10.5tags: List[str] = []items = {"foo": {"name": "Foo", "price": 50.2},"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []}, }@app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True) async def read_item(item_id: str):return items[item_id]


如果參數(shù) 改為 False,或者 刪除該參數(shù),未設(shè)置的值 也顯示出來了

4. response_model_include 和 response_model_exclude

它們接收一個由屬性名稱 str 組成的 set 來包含(忽略其他的)或者排除(包含其他的)這些屬性

  • response_model_include, 只包含指定字段
  • response_model_exclude,排除指定字段
from typing import Optional, List from fastapi import Cookie, FastAPI, Header from pydantic import BaseModel, EmailStrapp = FastAPI()class Item(BaseModel):name: strdescription: Optional[str] = Noneprice: floattax: float = 10.5items = {"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,response_model_include={"name", "description"}, # { } 表示 set, 使用 [ ] 也可以 ) 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]


5. 代碼復(fù)用:繼承

from typing import Optional from fastapi import FastAPI from pydantic import EmailStr, BaseModel app = FastAPI()class UserIn(BaseModel):username: strpassword: stremail: EmailStrfull_name: Optional[str] = Noneclass UserOut(BaseModel):username: stremail: EmailStrfull_name: Optional[str] = Noneclass UserInDB(BaseModel):username: strhashed_password: stremail: EmailStrfull_name: Optional[str] = Nonedef fake_password_hasher(raw_password: str):return "supersecret" + raw_passworddef fake_save_user(user_in: UserIn):hashed_password = fake_password_hasher(user_in.password)user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)# 使用user_in的數(shù)據(jù)初始化UserInDB , 并添加hashed_password字段print("User saved! ..not really")return user_in_db@app.post("/user/", response_model=UserOut) async def create_user(user_in: UserIn):user_saved = fake_save_user(user_in)return user_saved
  • 通過繼承進(jìn)行復(fù)用
from typing import Optional from fastapi import FastAPI from pydantic import EmailStr, BaseModel app = FastAPI()class UserBase(BaseModel):username: stremail: EmailStrfull_name: Optional[str] = Noneclass UserIn(UserBase):password: strclass UserOut(UserBase):passclass UserInDB(UserBase):hashed_password: strdef fake_password_hasher(raw_password: str):return "supersecret" + raw_passworddef fake_save_user(user_in: UserIn):hashed_password = fake_password_hasher(user_in.password)user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)# 使用user_in的數(shù)據(jù)初始化UserInDB , 并添加hashed_password字段print("User saved! ..not really")return user_in_db@app.post("/user/", response_model=UserOut) async def create_user(user_in: UserIn):user_saved = fake_save_user(user_in)return user_saved

6. Union

  • 響應(yīng)將是 多種類型中的 任何一種
from typing import Optional, Union class BaseItem(BaseModel):description: strtype: strclass CarItem(BaseItem):type = "car"class PlaneItem(BaseItem):type = "plane"size: intitems = {"item1": {"description": "All my friends drive a low rider", "type": "car"},"item2": {"description": "Music is my aeroplane, it's my aeroplane","type": "plane","size": 5,}, }@app.get("/items/{item_id}", response_model=Union[PlaneItem, CarItem]) async def read_item(item_id: str):return items[item_id]

7. 任意 dict 的響應(yīng)

  • 對于事先不知道 key 的,可以直接定義字典及其 k, v 的類型
@app.get("/keyword-weights/", response_model=Dict[str, float]) async def read_keyword_weights():return {"foo": 2.3, "bar": 3.4}

8. 響應(yīng)狀態(tài)碼

  • 裝飾器函數(shù)內(nèi) 使用 status_code 參數(shù)來聲明用于響應(yīng)的 HTTP 狀態(tài)碼
@app.get("/items/{item_id}", response_model=Union[PlaneItem, CarItem],status_code=208) async def read_item(item_id: str):return items[item_id]


關(guān)于 HTTP 狀態(tài)碼

在 HTTP 協(xié)議中,你將發(fā)送 3 位數(shù)的數(shù)字狀態(tài)碼作為響應(yīng)的一部分。

  • 100 及以上狀態(tài)碼用于「消息」響應(yīng)。你很少直接使用它們。具有這些狀態(tài)代碼的響應(yīng)不能帶有響應(yīng)體。

  • 200 及以上狀態(tài)碼用于「成功」響應(yīng)。這些是你最常使用的。

    • 200 是默認(rèn)狀態(tài)代碼,它表示一切「正常」。
    • 另一個例子會是 201,「已創(chuàng)建」。它通常在數(shù)據(jù)庫中創(chuàng)建了一條新記錄后使用。
    • 一個特殊的例子是 204,「無內(nèi)容」。此響應(yīng)在沒有內(nèi)容返回給客戶端時使用,因此該響應(yīng)不能包含響應(yīng)體。
  • 300 及以上狀態(tài)碼用于「重定向」。具有這些狀態(tài)碼的響應(yīng)可能有或者可能沒有響應(yīng)體,但 304「未修改」是個例外,該響應(yīng)不得含有響應(yīng)體。

  • 400 及以上狀態(tài)碼用于「客戶端錯誤」響應(yīng)。這些可能是你第二常使用的類型。

    • 一個例子是 404,用于「未找到」響應(yīng)。
    • 對于來自客戶端的一般錯誤,你可以只使用 400。
  • 500 及以上狀態(tài)碼用于服務(wù)器端錯誤。你幾乎永遠(yuǎn)不會直接使用它們。當(dāng)你的應(yīng)用程序代碼或服務(wù)器中的某些部分出現(xiàn)問題時,它將自動返回這些狀態(tài)代碼之一。

from fastapi import FastAPI, status status_code=status.HTTP_201_CREATED # 可以使用代碼補(bǔ)全,不必記住

9. 表單參數(shù)

  • 接收的不是 JSON,而是表單字段時,要使用 Form
from fastapi import FastAPI, Form app = FastAPI()@app.post("/login/") async def login(username: str = Form(...),password: str = Form(...)):return {"username" : username}

總結(jié)

以上是生活随笔為你收集整理的fastapi 响应模型 / 响应状态码 / 表单参数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。