iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0
自我挑戰組

從零打造客製化 AI 聊天機器人系列 第 7

[從零打造客製化 AI 聊天機器人] 初步學習 FastAPI ,新手友善

  • 分享至 

  • xImage
  •  

FastAPI 是一個在 Python 中建構 RESTful API 的 Web 框架,接下來跟大家介紹 FastAPI 有什麼優點以及要如何快速上手。

FastAPI 優點:
快速:根據多項測試,目前 FastAPI 是所有 Python 框架當中,速度最快的。
易用:設計上易於使用和學習,大幅減少閱讀文件的時間,新手學習成本低。
驗證資料格式:驗證前端輸入的資料格式。
自動生成 API 文件:可以自動生成 Swagger 和 ReDoc 文件。
WebSocket:可以整合 WebSocket 雙向即時系統。

接下來就教大家如何安裝 FastAPI 和 如何快速上手:

1. 已經安裝 Python 3.10 以上的版本

2. 安裝 FastAPI

pip install fastapi

3. 安裝 uvicorn(ASGI伺服器)

pip install "uvicorn[standard]"

4. 創建一個簡單的路由
建立一個 main.py 檔案

from fastapi import FastAPI # 載入 fastapi
app = FastAPI() # 建立 fastapi 物件

# 建立網站首頁
@app.get("/")
def index():
    return "Hello World"

5. 啟動後端程式

uvicorn main:app --reload
# uvicorn 檔案名稱:FastAPI儲存物物件名稱 --reload

https://ithelp.ithome.com.tw/upload/images/20240920/20169415S5kuJdemp3.jpg
http://127.0.0.1:8000 上啟動網頁,--reload 選項允許在修改程式時自動重啟服務
https://ithelp.ithome.com.tw/upload/images/20240920/20169415Hmnkz2nGqo.jpg

6. 中斷程式
CTRL + C

7. 自動生成 API 文件
Swagger UI:http://127.0.0.1:8000/docs
ReDoc:http://127.0.0.1:8000/redoc
文件會依據 API 結構自動生成,並隨著 API 修改自動更新

8. 處理請求參數

  • 路徑參數 Path Parameters
    這個參數可以嵌入在 URL 路徑中使用,例如:URL /user/{name} name 是路徑參數。

    @app.get("/user/{name}")
    def getUser(name):
      return{"echo":"Hello "+name}
    

    http://127.0.0.1:8000/user/jerry 得到以下結果
    https://ithelp.ithome.com.tw/upload/images/20240920/20169415DFu8s3b2Bn.jpg

  • 輸入驗證 Input Validation

    • 路徑參數驗證

      @app.get("/class/{id}")
      def getClass(id:int):
        return{"data":"教室 id 是 "+ id}
      

      id 被定義為 int 型別,FastAPI 會判斷傳入 id 是否為整數,如果非整數就會返回 422。
      https://ithelp.ithome.com.tw/upload/images/20240920/201694150KNVk7RC7X.jpg

      https://ithelp.ithome.com.tw/upload/images/20240920/20169415HaYoiBwH1X.jpg

    • 查詢參數驗證

      @app.get("/items/")
      async def read_item(first: int = 0, last: int = 10):
        return {"first": first, "last": last}
      

      first和 last都是查詢參數,定義為 int 型別。如果用戶傳遞了非整數值,FastAPI 會自動返回錯誤。

    • Pydantic 模型進行請求體驗證
      Pydantic 是一個 Python 資料驗證函式庫,程式碼中定義類別 class ,讓類別繼承 Pydantic 的 BaseMode ,這樣就可自由使用。

      from pydantic import BaseModel
      
      class Products(BaseModel):
        name: str
        description: str = None
        price: float
      
      @app.post("/products")
      async def create_products(products: Products):
           return products
      

9. 部署 FastAPI 應用
Docker 或托管平台(AWS、GCP)

以上就是簡單的 FastAPI 介紹


上一篇
[從零打造客製化 AI 聊天機器人] 初步學習 Python,AI 首選語言
下一篇
[從零打造客製化 AI 聊天機器人] 初步學習 ChromaDB,存儲和檢索資料
系列文
從零打造客製化 AI 聊天機器人14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言