核心功能
定義路由
FastAPI 中定義路由的方式主要有兩種,一種是使用 FastAPI 應(yīng)用實例的方法(例如 app.get()
),一種是使用裝飾器(例如 @app.get()
),它們的用法和作用略有不同。
-
方式1:使用 FastAPI 應(yīng)用實例的方法
app.get()
、app.post()
等方法用于直接在應(yīng)用實例上定義路由。這些方法接受路徑字符串和處理函數(shù)作為參數(shù),將指定的路徑映射到相應(yīng)的處理函數(shù),用于處理該路徑上的請求。
這種方式適用于在全局范圍內(nèi)定義路由,將路由直接添加到應(yīng)用程序中。
from fastapi import FastAPI def read_root(): return {"message": "Hello, World"} app = FastAPI() app.get("/", read_root)
-
方式2:使用裝飾器
@app.get()
、@app.post()
等裝飾器語法,用于在路由處理函數(shù)上方添加裝飾器,將處理函數(shù)與特定的路徑和 HTTP 方法關(guān)聯(lián)起來。裝飾器方式允許直接在路由處理函數(shù)上使用裝飾器來定義路徑、HTTP 方法、響應(yīng)模型等屬性。
這種方式更直觀,將路由相關(guān)的信息集中在處理函數(shù)上,使代碼更易讀和維護。適用于局部范圍內(nèi)定義路由。
from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"message": "Hello, World"}
-
拓展:匹配所有路徑的方式
@app.get("/files/{file_path:path}") # :path 代表任意路徑 async def read_file(file_path: str): return {"file_path": file_path}
路由分組
-
FastAPI 允許將路由組織成分組,以更好地組織和管理 API 端點。這對于具有多個相關(guān)路由的應(yīng)用程序特別有用。分組可以保持代碼的清晰性和可維護性。
路由分組有助于保持代碼的整潔和可讀性,還可以在文檔中更好地組織和呈現(xiàn) API 端點。
可以根據(jù)需求創(chuàng)建多個分組,在分組中將相關(guān)的路由放在一起,同時還可以將路由分組放到不同的模塊,比如可以創(chuàng)建一個
items.py
文件,其中包含所有與 items 相關(guān)的路由,然后,在主函數(shù)模塊main.py
中導(dǎo)入并將分組添加到應(yīng)用程序。 -
APIRouter 模塊的方法:
- APIRouter() :創(chuàng)建一個路由分組實例
-
FastAPI 模塊的方法:
-
include_router() :將分組添加到應(yīng)用程序
- router 參數(shù):指定路由分組。默認參數(shù),必傳
-
prefix 參數(shù):指定分組的前綴路徑,選傳,缺省默認為
""
- tags 參數(shù):指定分組的標簽,以便于文檔化和分類
-
include_router() :將分組添加到應(yīng)用程序
-
示例
from fastapi import FastAPI, APIRouter app = FastAPI() # 創(chuàng)建一個路由分組 router = APIRouter() # 將路由添加到分組 @router.get("/") def read_root(): return {"message": "Root"} @router.get("/items/") def read_items(): return {"message": "Items"} # 將分組添加到應(yīng)用程序 app.include_router(router, prefix="/group1", tags=["Group 1"]) # 創(chuàng)建另一個路由分組 router2 = APIRouter() @router2.get("/") def read_another_root(): return {"message": "Another Root"} @router2.get("/things/") def read_things(): return {"message": "Things"} # 將第二個分組添加到應(yīng)用程序 app.include_router(router2, prefix="/group2", tags=["Group 2"])
路徑參數(shù)
聲明路徑參數(shù)
-
路徑參數(shù):FastAPI 通過在路徑參數(shù)兩邊添加
{}
聲明動態(tài)路徑參數(shù)@app.get("/items/{item_id}") def read_item(item_id: int): return {"item_id": item_id}
路徑參數(shù) item_id 的值將作為參數(shù) item_id 傳遞給函數(shù)。
- 若 item_id 未聲明(限制)類型,則輸入字符串還是數(shù)字均可,不過會默認轉(zhuǎn)化成字符串。
- 若 item_id 聲明(限制)了類型,則只能按照提前聲明好的類型進行傳參
-
包含路徑參數(shù)的路由必須聲明在路徑前綴相同的普通路徑之后!
舉個例子,假設(shè)現(xiàn)有兩個具有相同路徑前綴的路徑:
-
/users/me
,用來獲取關(guān)于當前用戶的數(shù)據(jù)的普通路徑 -
/users/{user_id}
,用來通過用戶 ID 獲取關(guān)于特定用戶的數(shù)據(jù)的包含路徑參數(shù)的路由
由于路徑操作是按順序依次運行的,所以需要確保路徑
/users/me
聲明在路徑/users/{user_id}
之前!否則,
/users/{user_id}
的路徑還將與/users/me
相匹配,"認為"自己正在接收一個值為 “me” 的 user_id 參數(shù)。from fastapi import FastAPI app = FastAPI() @app.get("/users/me") async def read_user_me(): return {"user_id": "the current user"} @app.get("/users/{user_id}") async def read_user(user_id: str): return {"user_id": user_id}
-
-
預(yù)設(shè)值
有時只需要給路徑參數(shù)傳遞幾個常用并且固定的有效值,那么就可以通過枚舉來定制預(yù)設(shè)值。
注:枚舉(enums)從 3.4 版本起在 Python 中可用。
from enum import Enum # 創(chuàng)建一個 Enum 類 class ModelName(str, Enum): yinyu = "yinyu_v" s1 = "s1_v" s2 = "s2_v" # 包含枚舉的路徑參數(shù) ## 路徑參數(shù) model_name 的值將傳遞給函數(shù) get_model 的參數(shù) model_name,并且這個值的取值范圍只能是 ModelName 枚舉類中類屬性的值。 @app.get("/models/{model_name}") async def get_model(model_name: ModelName): # 第 1 種判斷方式 if model_name is ModelName.yinyu: return {"model_name": model_name, "message": "yinyu get"} # 第 2 種判斷方式,效果一樣 if model_name.value == "s1_name": return {"model_name": model_name, "message": "s1 get"} else: return {"model_name": ModelName.s2, "message": "s2 get"}
fastapi.Path(校驗路徑參數(shù))
在 FastAPI 中,fastapi.Path
是一個用于聲明路徑參數(shù)的類,它提供了更多的參數(shù)配置選項,允許定義路徑參數(shù)的類型、默認值、校驗規(guī)則等。使用 fastapi.Path
可以更精細地控制路徑參數(shù)的行為。
常用可選傳參數(shù):
-
default
:指定路徑參數(shù)的默認值。注意:因路徑參數(shù)總是必需的,若想傳參 default,只能設(shè)置
default=...
,表示顯式的將其標記為必需參數(shù)。 -
title
:在自動生成的 API 文檔中,用于顯示路徑參數(shù)的標題,提供更好的文檔說明。 -
description
:在自動生成的 API 文檔中,用于顯示路徑參數(shù)的詳細描述,提供更詳細的文檔說明。 -
min_length
和max_length
:用于限制路徑參數(shù)的字符串長度范圍。 -
min
和max
:用于限制路徑參數(shù)的數(shù)值范圍,適用于數(shù)值類型的路徑參數(shù)。 -
regex
:使用正則表達式校驗路徑參數(shù)的值,可以使用字符串形式的正則表達式。 -
deprecated
:將路徑參數(shù)標記為已棄用,用于指示用戶不應(yīng)再使用該參數(shù)。 -
example
:在自動生成的 API 文檔中,用于為路徑參數(shù)提供示例值,幫助用戶理解如何使用該參數(shù)。 -
gt
、ge
、lt
、le
:用于設(shè)置數(shù)值類型路徑參數(shù)的大小比較,分別表示大于、大于等于、小于、小于等于。 -
const
:將路徑參數(shù)設(shè)置為一個常量值,這可以用于實現(xiàn)一些特定的路由匹配需求。
查詢參數(shù)
聲明查詢參數(shù)
-
查詢參數(shù)
在 Web 開發(fā)中,查詢參數(shù)(Query Parameters)是通過 URL 中的參數(shù)鍵值對來傳遞額外的信息給服務(wù)器的一種方式。這些參數(shù)通常用于過濾、排序、分頁等操作。
查詢參數(shù)通常出現(xiàn)在 URL 的問號(?)后面,每個查詢參數(shù)由參數(shù)名和參數(shù)值組成,用等號(=)連接。多個查詢參數(shù)之間使用與號(&)分隔。
-
FastAPI 聲明查詢參數(shù):
在路由函數(shù)的參數(shù)列表聲明不屬于路徑參數(shù)的其他函數(shù)參數(shù),將被自動解釋為查詢參數(shù)!
查詢參數(shù)可以設(shè)置默認值:
- 若設(shè)置了默認值,則該參數(shù)是可選傳的。默認值可以設(shè)置為 None
- 若未設(shè)置默認值,則該參數(shù)是必傳的,未傳參會報錯
FastAPI 可以將參數(shù)直接添加到路由函數(shù)的參數(shù)列表來獲取查詢參數(shù)(可以設(shè)置默認值,若不設(shè)置默認值的話,未傳參會報錯)
@app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): # q是一個查詢參數(shù),可以接受字符串類型的值 return {"item_id": item_id, "q": q} # 調(diào)用:localhost:8000/items/2?q=hhh
-
bool 類型轉(zhuǎn)換
聲明為 bool 類型的查詢參數(shù),可以將傳參 1、True 、true、on、yes 自動類型轉(zhuǎn)換為 True
fastapi.Query(校驗查詢參數(shù))
-
typing.Union :是 Python 中的一個類型提示工具,用于表示多個類型的聯(lián)合。它通常與 Union 類型進行配合使用。
在類型注釋中,可以使用 typing.Union 來明確指定一個變量的類型可以是多個類型中的一個
-
fastapi.Query :是 FastAPI 框架中用于處理查詢參數(shù)的一個工具,并允許指定各種參數(shù)來控制查詢參數(shù)的類型、默認值、驗證等。以下是一些常用的可選傳參數(shù):
-
default
:指定查詢參數(shù)的默認值。如果請求中沒有提供該查詢參數(shù),將使用默認值??梢晕恢脗鲄?。聲明為必傳傳參數(shù):
-
方式1:不指定默認值即為必傳參數(shù)
-
方式2:指定
default=...
-
方式3:指定
default=Required
注:需導(dǎo)包
from pydantic import Required
-
-
title
:用于自動生成的 API 文檔中的標題,使文檔更加清晰易懂。 -
description
:在自動生成的 API 文檔中顯示有關(guān)查詢參數(shù)的詳細說明。 -
alias
:指定查詢參數(shù)的別名。當希望在函數(shù)中使用不同的名稱來引用查詢參數(shù)時,可以使用這個參數(shù)。 -
regex
:使用正則表達式對查詢參數(shù)進行驗證。只有匹配正則表達式的參數(shù)值才會被接受。 -
min_length
和max_length
:限制查詢參數(shù)值的最小和最大長度。 -
min
和max
:限制查詢參數(shù)值的最小和最大值(僅適用于數(shù)字類型的參數(shù))。 -
gt
、ge
、lt
、le
:分別用于指定查詢參數(shù)的大于、大于等于、小于、小于等于的值(僅適用于數(shù)字類型的參數(shù))。 -
multiple
:指定查詢參數(shù)是否可以有多個值,即是否允許使用多個相同名稱的查詢參數(shù)。一般用于 list 類型的查詢參數(shù)
-
deprecated
:指定查詢參數(shù)是否已棄用。如果設(shè)置為
True
,在自動生成的 API 文檔中將顯示該參數(shù)已被棄用的信息。
-
-
代碼示例:
from typing import Union from fastapi import FastAPI,Query @app.get("/items21/") async def read_items(q: Union[str, None] = Query(default=None), a: str = Query(default=None, max_length=50, min_length=3) b: Union[str, None] = Query(default=None, regex="^fixedquery$") ): query_items = {"q": q} return query_items
請求體 與 響應(yīng)模型
-
請求體
使用 Pydantic 庫定義數(shù)據(jù)模型,可以輕松處理請求體。
from pydantic import BaseModel # 定義Item模型 class Item(BaseModel): name: str description: str = None price: float tax: float = None @app.post("/items/") def create_item(item: Item): # 使用Item模型定義了請求體的結(jié)構(gòu),并將其用作create_item函數(shù)的參數(shù) return item
-
響應(yīng)模型
通過為路由設(shè)置 response_model 參數(shù),可以定義響應(yīng)數(shù)據(jù)的結(jié)構(gòu)。
from pydantic import BaseModel class Item(BaseModel): name: str description: str = None price: float tax: float = None @app.post("/items/", response_model=Item) def create_item(item: Item): return item
依賴注入
-
FastAPI 支持依賴注入,可以方便地管理和復(fù)用代碼。
在 FastAPI 中,依賴注入是一種強大的功能,它允許將功能(如數(shù)據(jù)庫連接、驗證邏輯等)注入到路由處理函數(shù)中,以便更好地組織和管理代碼,并實現(xiàn)解耦和可測試性。
依賴注入使得能夠在需要時將依賴項提供給函數(shù),而不是在函數(shù)內(nèi)部創(chuàng)建這些依賴項。
依賴注入的優(yōu)勢在于它可以將復(fù)雜的邏輯從路由處理函數(shù)中分離出來,使代碼更加清晰和可維護。
from fastapi import FastAPI, Depends app = FastAPI() # 依賴項,模擬數(shù)據(jù)庫連接 def get_db_connection(): db_connection = "fake_db_connection" return db_connection # 路由處理函數(shù),注入依賴項 @app.get("/items/") async def read_items(db: str = Depends(get_db_connection)): return {"message": "Items retrieved", "db_connection": db}
異常處理
-
通過自定義異常處理程序來處理應(yīng)用程序中的錯誤
from fastapi import HTTPException @app.get("/items/{item_id}") def read_item(item_id: int): if item_id < 1: raise HTTPException(status_code=400, detail="Item not found") return {"item_id": item_id}
文件上傳
-
使用 fastapi.UploadFile 類型來接收上傳的文件數(shù)據(jù)
from fastapi import FastAPI, UploadFile from fastapi.staticfiles import StaticFiles import os app = FastAPI() # 配置靜態(tài)文件路徑 app.mount("/static", StaticFiles(directory="static"), name="static") @app.post("/file_upload") async def file_upload(file: UploadFile): # 接收文件 res = await file.read() # 寫到本地 predict_img_path = os.path.join('static', file.filename) with open(predict_img_path, "wb") as f: f.write(res) return {"code": 1, "msg": "上傳成功:{}".format(file.filename)} if __name__ == '__main__': import uvicorn uvicorn.run(app="main:app", host="0.0.0.0", port=2333)
拓展:上傳文件
-
方式1:
import requests import json if __name__ == '__main__': # 上傳一張圖 file_path = r'E:\工具測試數(shù)據(jù)\封面上傳測試\img\1825513ec0b.png' url = "http://127.0.0.1:2333/file_upload" data = {"file": open(file_path, 'rb')} res = requests.post(url=url, files=data, verify=False) print(json.loads(res.content)) # {'code': 1, 'msg': '上傳成功:7f63f6711f5f57d9.jpg'}
-
方式2:
import requests import json import os from urllib3 import encode_multipart_formdata if __name__ == '__main__': # 上傳一張圖 file_path = r'E:\工具測試數(shù)據(jù)\封面上傳測試\img\1825513ec0b.png' url = "http://127.0.0.1:2333/file_upload" with open(file_path, 'rb') as f: file_name = os.path.split(file_path)[-1] file = {"file": (file_name, f.read())} encode_data = encode_multipart_formdata(file) data = encode_data[0] content_type = encode_data[1] headers = { 'Content-Type': content_type } res = requests.post(url, headers=headers, data=data) print(json.loads(res.content)) # {'code': 1, 'msg': '上傳成功:1825513ec0b.png'}
Request (請求對象 )
-
request 對象
FastAPI 可以在路由處理函數(shù)中使用 fastapi.Request 模型來獲取請求的詳細信息,如頭部、查詢參數(shù)等。
from fastapi import FastAPI, Request @app.get("/user-agent/") def read_user_agent(request: Request): # 獲取請求頭 headers = request.headers user_agent = headers.get("user-agent") return {"user_agent": user_agent}
-
請求頭部中的信息
FastAPI 可以在路由處理函數(shù)中使用 fastapi.Header 模型來獲取請求頭部中的信息,例如 user_agent 等
from fastapi import FastAPI, Header @app.get("/headers/") def read_headers(user_agent: str = Header(None)): return {"User-Agent": user_agent}
安全性
- FastAPI 提供了多種安全性機制,用于保護 Web 應(yīng)用免受常見的安全風(fēng)險和攻擊。以下是 FastAPI 中一些常見的安全性機制:
-
身份驗證(Authentication):FastAPI 支持多種身份驗證方法,例如 OAuth2、JWT(JSON Web Tokens)、基本身份驗證等。可以使用
Depends
來在路由中驗證用戶的身份,并且只有通過身份驗證的用戶才能訪問受保護的資源。 - 授權(quán)(Authorization):一旦用戶通過身份驗證,F(xiàn)astAPI 還允許實施授權(quán)機制來確定用戶是否有權(quán)訪問特定的資源。這可以通過自定義依賴項或裝飾器來實現(xiàn)。
- CORS(跨源資源共享):CORS 是一種安全機制,用于控制跨域請求。FastAPI 允許配置 CORS 策略,以確保只有特定來源的請求能夠訪問你的 API。
- CSRF(跨站請求偽造)防御:FastAPI 提供了內(nèi)置的 CSRF 保護,可以防止 CSRF 攻擊,保護你的用戶免受惡意網(wǎng)站的攻擊。
- 安全頭部(Security Headers):FastAPI 自動添加一些安全頭部到響應(yīng)中,保護應(yīng)用程序免受一些常見的網(wǎng)絡(luò)攻擊,如點擊劫持、XSS(跨站腳本攻擊)等。
-
密碼哈希和存儲:FastAPI 鼓勵使用密碼哈希來存儲用戶密碼,以保護用戶隱私??梢允褂脙?nèi)置的
Passlib
庫來進行密碼哈希和驗證。 - 請求驗證和輸入校驗:FastAPI 內(nèi)置了請求驗證和輸入校驗機制,以過濾和驗證傳入的數(shù)據(jù),防止不良輸入和惡意數(shù)據(jù)攻擊。
- 日志和審計:FastAPI 允許記錄應(yīng)用程序的活動,以便在發(fā)生安全事件時進行審計和分析。
- HTTPS 支持:FastAPI 支持通過 HTTPS 提供加密連接,以確保數(shù)據(jù)在傳輸過程中的安全性。
-
身份驗證(Authentication):FastAPI 支持多種身份驗證方法,例如 OAuth2、JWT(JSON Web Tokens)、基本身份驗證等。可以使用
拓展
訪問 Fast API 接口文檔
-
Swagger UI 提供的 api 文檔
ip:端口/docs(默認 127.0.0.1:8000/docs)
-
ReDoc 提供的 api 文檔
ip:端口/docs(默認 127.0.0.1:8000/redoc)文章來源:http://www.zghlxwxcb.cn/news/detail-752347.html
FastAPI 項目的基本目錄結(jié)構(gòu)
my_project/
├── app/
│ ├── apis/
│ │ ├── __init__.py
│ │ ├── auth.py
│ │ ├── items.py
│ │ └── users.py
│ ├── core/
│ │ ├── __init__.py
│ │ ├── config.py
│ │ ├── security.py
│ │ └── sqlalchemy.py
│ ├── db/
│ │ ├── __init__.py
│ │ └── base.py
│ ├── main.py
│ └── models/
│ ├── __init__.py
│ ├── item.py
│ └── user.py
├── docker-compose.yml
├── Dockerfile
├── README.md
└── requirements.txt
- app/:用于存放應(yīng)用程序的主要代碼。包含 API 定義、業(yè)務(wù)邏輯、數(shù)據(jù)庫連接等。
- app/apis/:API 路由和業(yè)務(wù)邏輯實現(xiàn)的目錄。
- app/core/:配置、鑒權(quán)、數(shù)據(jù)庫連接等核心功能的實現(xiàn)。
- app/db/:數(shù)據(jù)庫模型的定義,以及數(shù)據(jù)庫相關(guān)的代碼。
- app/models/:ORM 模型定義,實現(xiàn)業(yè)務(wù)邏輯和數(shù)據(jù)庫操作的映射。
- app/main.py:FastAPI 應(yīng)用程序的啟動文件,包括應(yīng)用程序的初始化、路由注冊等。
- docker-compose.yml:Docker-Compose 配置文件
- Dockerfile:應(yīng)用程序Docker鏡像的構(gòu)建文件
- README.md:項目文檔
- requirements.txt:項目依賴清單
此外,還可以根據(jù)項目需要添加其他目錄和文件,例如靜態(tài)文件目錄、測試目錄、文檔目錄等。但是,無論怎樣組織FastAPI項目結(jié)構(gòu),都需要保證代碼清晰明了、易于維護。文章來源地址http://www.zghlxwxcb.cn/news/detail-752347.html
到了這里,關(guān)于FastAPI 庫(Python 的 Web 框架)基本使用指南(二)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!