在Web開發領域,Python一直是深受開發者喜愛的語言。其中,很多人使用Python來搭建RESTful API,而FastAPI框架作為Python中的一枚新星,它有著很多優秀的特性,比如高性能、易於開發、易於測試等等。本文將從多個方面對FastAPI框架做詳細的闡述,包括FastAPI框架的介紹、安裝、基本使用、模型和資料庫、WebSocket等等。
一、介紹
FastAPI是一個基於Python 3.6+的快速Web框架,它具有以下特點:
- 快速:使用FastAPI可以快速構建高性能的RESTful API。
- 易於開發:具有易於使用和易於編寫的API設計,同時FastAPI還提供了很多代碼生成的特性以方便開發。
- 快速學習:FastAPI框架有著清晰的文檔和例子,使任何人都可以簡單快速地學習和開始使用它。
- 標準化:FastAPI遵循市場上最好的實踐,並充分利用現代Python3中的特性(如類型提示等)。
二、安裝
在安裝FastAPI之前,需要首先安裝Python和pip工具。
1、在終端中輸入以下內容進行安裝:
pip install fastapi
2、安裝完FastAPI後,可以輸入以下內容來安裝uvicorn(這是一個基於asgi的高性能Web伺服器):
pip install uvicorn
三、基本使用
在安裝完成之後,就可以利用FastAPI框架開始構建你的API了。下面是一個很基礎的FastAPI示例:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
上述代碼中,我們先導入了FastAPI框架,然後創建了一個新的FastAPI實例(app)。不同於其他框架,在FastAPI中,每個路由操作都只是簡單的Python函數。使用裝飾器(如@app.get)來告訴FastAPI框架我們對API的請求方式(GET, POST等等)以及對應的URL路徑(如/items/{item_id})。
對於我們的read_item函數,我們指定了兩個參數:item_id和q,它們都是必填項和可選項。在FastAPI的API請求中,使用類型提示可以驗證請求中的數據類型是否正確,並且可以根據默認值自動推斷參數是否為必填項。
四、模型和資料庫
在實際使用時,你需要保存很多不同的數據。在FastAPI框架中,我們可以使用pydantic模型來驗證數據。下面是一個例子:
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
@app.post("/items/")
async def create_item(item: Item):
return item
上述代碼中,我們先導入相關的依賴,然後定義了一個Item模型類(是一個繼承自BaseModel的Python類)。在Item類中,定義了三個屬性:name(str類型)、price(float類型)和is_offer(bool類型)。其中,is_offer屬性是可選的,默認為None。
我們接著定義了一個create_item函數,其中有一個參數item(即Item類型)。對於通過FastAPI框架使用的API請求,如果請求的數據不符合Item的定義,FastAPI框架將會向客戶端返回400錯誤。在代碼中,我們返回了剛剛收到的item值。
在實際使用中,我們需要將數據存儲到資料庫中。在FastAPI框架中,我們可以利用SQLAlchemy或ORM(對象關係映射)框架,以更加高效和安全的方式來管理數據和資料庫。下面是一個例子:
from fastapi import FastAPI
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Integer, String, Column
app = FastAPI()
SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)
status = Column(String, index=True)
@app.post("/items/")
async def create_item(item: Item):
db_item = Item(title=item.title, description=item.description, status=item.status)
db = SessionLocal()
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
上述代碼中,我們引入了SQLAlchemy工具,定義了一個Item表並且創建了一個create_item函數。在這個函數中,我們創建了一個資料庫環境,將Item插入到資料庫中(在這裡是postgreSQL)並返回這個item。在實際項目中,你可以根據自己需要的資料庫類型來改變這裡的資料庫連接方法。
五、WebSocket
FastAPI框架同樣支持伺服器端和客戶端WebSocket。下面是一個例子:
伺服器端:
from fastapi import FastAPI, WebSocket
app = FastAPI()
class ConnectionManager:
def __init__(self):
self.active_connections = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def broadcast(self, data: str):
for connection in self.active_connections:
await connection.send_text(data)
manager = ConnectionManager()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"Client says: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(f"Client left!")
客戶端:
from fastapi import FastAPI
import websocket
app = FastAPI()
@app.get("/ws/")
async def websocket():
ws = websocket.create_connection("ws://localhost:8000/ws/")
ws.send("Hello, Server")
result = ws.recv()
return {"Result: ": result}
上述代碼中,我們定義了一個WebSocket伺服器端和客戶端,其中WebSocket連接管理器類ConnectionManager維護了所有活動連接的列表。在伺服器端代碼中,我們定義了一個WebSocket連接點,客戶端代碼中我們定義了一個客戶端API,使用websocket庫向伺服器端建立WebSocket連接並發送消息。
六、結語
通過本文對FastAPI框架的深入講解,相信大家已經對FastAPI的基本使用和更多高級特性有了更深層次的了解。FastAPI憑藉其高性能、易於開發的優點,很快成為了Python Web開發的熱門選擇之一。希望本文可以幫助您更好地了解和使用它。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/254199.html