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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

fastapi 用户指南(路径参数、查询参数、请求体)

發布時間:2024/7/5 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 fastapi 用户指南(路径参数、查询参数、请求体) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 1. 第一步
      • 1.1 小結
    • 2. 路徑參數
      • 2.1 順序很重要
      • 2.2 預設值
      • 2.3 包含路徑的路徑參數
    • 3. 查詢參數
      • 3.1 查詢參數類型轉換
    • 4. 請求體

learn from https://fastapi.tiangolo.com/zh/tutorial/

1. 第一步

  • pip install fastapi[all]
from fastapi import FastAPI my_app = FastAPI() # my_app 實例, 名字對應于 終端里的 @my_app.get("/") async def root():return {"message" : "Hello World"}

  • http 操作:
    POST:創建數據。
    GET:讀取數據。
    PUT:更新數據。
    DELETE:刪除數據。

@my_app.get("/") 告訴 FastAPI 在它下方的函數負責處理如下訪問請求:

  • 請求路徑為 /
  • 使用 get 操作

函數可以返回一個 dict、list,像 str、int 一樣的單個值,等等。還可以返回 Pydantic 模型

1.1 小結

  • 導入 FastAPI
  • 創建一個 app 實例
  • 編寫一個路徑操作裝飾器(如 @app.get("/"))
  • 編寫一個路徑操作函數(如上面的 def root(): ...)
  • 運行開發服務器(如 uvicorn main:app --reload)

2. 路徑參數

  • 函數參數,與 { } 內的名字,保持一致
@my_app.get("/items/{item_id}") async def read_item(item_id): # 要跟上面的 {} 內保持一致return {"itemid": item_id} # 返回字符串
  • 參數類型限制 : type,參數類型不匹配會報錯
@my_app.get("/items/{item_id}") async def read_item(item_id: int): # 要跟上面的 {} 內保持一致return {"itemid": item_id} # 返回 int
  • 文檔 http://127.0.0.1:8000/docs,http://127.0.0.1:8000/redoc

2.1 順序很重要

@my_app.get("/users/me") async def read_user_me():return {"user_id": "the current user"}@my_app.get("/users/{user_id}") async def read_user(user_id: str):return {"user_id": user_id}


如果上面,兩個函數順序反了,如下結果

2.2 預設值

  • 使用 Enum
from enum import Enumapp = FastAPI()class ModelName(str, Enum): # 繼承string, 枚舉, 必須是字符串且是指定的枚舉值alexnet = "alexnet"resnet = "resnet"lenet = "lenet"@app.get("/models/{model_name}") async def get_model(model_name: ModelName):if model_name == ModelName.alexnet:return {"model_name": model_name, "message": "Deep Learning FTW!"}if model_name.value == "lenet":return {"model_name": model_name, "message": "LeCNN all the images"}return {"model_name": model_name, "message": "Have some residuals"}

可以使用 model_name.value 或通常來說 your_enum_member.value 來獲取實際的值


2.3 包含路徑的路徑參數

  • 參數 { } 內 參數名:path :前后均沒有空格,不加 :path 無法識別 帶有/ 的路徑參數
@app.get("/files/{file_path:path}") async def read_file(file_path: str):return {"file_path": file_path}

3. 查詢參數

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]@app.get("/items") async def read_item(skip: int = 0, limit: int = 10):return fake_items_db[skip:skip + limit]
  • 使用 ? 開始,參數間使用 & 分割
from typing import Optional @app.get("/items/{item_id}") async def read_item(item_id: str, q: Optional[str] = None):if q:return {"item_id": item_id, "q": q}return {"item_id": item_id}

3.1 查詢參數類型轉換

from typing import Optional@app.get("/items/{item_id}") async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):item = {"item_id" : item_id}if q:item.update({"q" : q})if not short:item.update({"description": "This is an amazing item that has a long description"})return item

輸入 short=,后面是 1,True, true, yes, on, On, YES 任意變形體都是一樣的效果,都是 true

  • 多個參數的順序沒影響,通過名字查找的
@app.get("/users/{user_id}/items/{item_id}") async def read_user_item(item_id: str, user_id: int, q: Optional[str] = None, short: bool = False ):item = {"item_id": item_id, "owner_id": user_id}if q:item.update({"q": q})if not short:item.update({"description": "This is an amazing item that has a long description"})return item
  • item_id: str, user_id: int, 更換兩個變量的位置,沒有關系

4. 請求體

請求體是客戶端發送給 API 的數據
響應體是 API 發送給客戶端的數據

使用 Pydantic 模型來聲明請求體

from typing import Optionalfrom Pinyin2Hanzi import Item from fastapi import FastAPI from pydantic import BaseModelclass Item(BaseModel):name: strdescription: Optional[str]=Noneprice:floattax:Optional[float] = Noneapp = FastAPI()@app.put("/items/{item_id}") async def create_item(item_id: int, item: Item, q: Optional[str] = None):result = {"item_id": item_id, **item.dict()}if q:result.update({"q": q})return result

  • 還可以同時聲明請求體、路徑參數和查詢參數。
    函數參數將依次按如下規則進行識別:
    1.如果在路徑中也聲明了該參數,它將被用作路徑參數
    2.如果參數屬于單一類型(比如 int、float、str、bool 等)它將被解釋為查詢參數
    3.如果參數的類型被聲明為一個 Pydantic 模型,它將被解釋為請求體

總結

以上是生活随笔為你收集整理的fastapi 用户指南(路径参数、查询参数、请求体)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。