
使用Node.js、Express和MySQL構建REST API
pip install uvicorn
uvicorn
是一個ASGI服務器,用于運行FastAPI應用。
讓我們從一個簡單的例子開始,創建一個基本的FastAPI應用。
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
在這個例子中,我們定義了兩個路由:
/
:返回一個簡單的問候消息/items/{item_id}
:接受一個整數參數,并返回該參數要運行這個應用,保存文件為main.py
,然后在終端中運行:
uvicorn main:app --reload
現在,你可以訪問http://127.0.0.1:8000
來查看你的API運行情況。
在處理高并發請求時,異步數據庫操作可以顯著提高API的性能。Python的asyncio
庫和支持異步的數據庫驅動程序使這成為可能。
對于本教程,我們將使用asyncpg
,這是一個用于PostgreSQL的高性能異步驅動程序。安裝asyncpg
:
pip install asyncpg
在FastAPI應用中,我們通常會創建一個數據庫連接池,以便高效地管理數據庫連接。
import asyncpg
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
async def startup():
app.state.pool = await asyncpg.create_pool(
"postgresql://user:password@localhost/dbname"
)
@app.on_event("shutdown")
async def shutdown():
await app.state.pool.close()
這段代碼在應用啟動時創建一個連接池,并在應用關閉時關閉它。
現在,讓我們創建一個更復雜的例子,展示如何在FastAPI中使用異步數據庫操作。假設我們有一個簡單的用戶管理API。
rom fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import asyncpg
app = FastAPI()
class User(BaseModel):
id: int
name: str
email: str
@app.on_event("startup")
async def startup():
app.state.pool = await asyncpg.create_pool(
"postgresql://user:password@localhost/dbname"
)
@app.on_event("shutdown")
async def shutdown():
await app.state.pool.close()
@app.post("/users/")
async def create_user(user: User):
async with app.state.pool.acquire() as connection:
await connection.execute('''
INSERT INTO users(id, name, email) VALUES($1, $2, $3)
''', user.id, user.name, user.email)
return {"message": "User created successfully"}
@app.get("/users/{user_id}")
async def read_user(user_id: int):
async with app.state.pool.acquire() as connection:
row = await connection.fetchrow(
'SELECT * FROM users WHERE id = $1', user_id
)
if not row:
raise HTTPException(status_code=404, detail="User not found")
return User(id=row['id'], name=row['name'], email=row['email'])
在這個例子中,我們定義了兩個端點:
/users/
(POST):創建新用戶/users/{user_id}
(GET):獲取特定用戶的信息這兩個端點都使用異步數據庫操作,允許FastAPI在等待數據庫響應時處理其他請求,從而提高整體性能。
為了進一步優化你的FastAPI應用性能,考慮以下幾點:
async def bulk_insert(users: List[User]):
async with app.state.pool.acquire() as conn:
await conn.executemany('''
INSERT INTO users(id, name, email) VALUES($1, $2, $3)
''', [(user.id, user.name, user.email) for user in users])
FastAPI結合異步數據庫操作為構建高性能、高并發的API提供了強大的工具。通過本教程,我們學習了如何:
記住,優化是一個持續的過程。隨著你的應用規模增長,你可能需要考慮更多的優化策略,如負載均衡、微服務架構等。
持續學習和實踐是提升API開發技能的關鍵。?希望這個教程能為你的FastAPI之旅提供一個良好的開端!
文章轉自微信公眾號@北野霜蘋