使用FastAPI构建高效微服务
1. 快速入门:搭建FastAPI开发环境
在任何软件开发工作中,首先了解项目的业务需求以及选择合适的框架、工具和部署平台是非常重要的。FastAPI是一个由Sebastian Ramirez创建的有前途的Python框架,它为开发者提供了构建REST API和微服务的最佳选择。
1.1 开发环境的搭建
为了确保顺利开发,我们需要准备以下环境:
- Python 3.8 或更高版本
-
安装了
uvicorn和fastapi的Python环境 - Git用于版本控制
- 编辑器如VS Code或PyCharm
以下是安装步骤:
-
创建一个新的虚拟环境:
python -m venv venv -
激活虚拟环境(Windows):
venv\Scripts\activate -
安装FastAPI和Uvicorn:
pip install fastapi uvicorn
1.2 初始化和配置FastAPI
创建一个名为
main.py
的文件,并编写以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}
启动应用:
uvicorn main:app --reload
1.3 REST API的设计与实现
FastAPI允许我们轻松地定义API端点。例如,创建一个简单的用户管理API:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str
app = FastAPI()
users_db = []
@app.post("/users/")
def create_user(user: User):
users_db.append(user)
return user
@app.get("/users/{user_id}")
def read_user(user_id: int):
for user in users_db:
if user.id == user_id:
return user
raise HTTPException(status_code=404, detail="User not found")
2. 核心特性:探索FastAPI的强大功能
FastAPI不仅仅是一个简单的Web框架,它还提供了许多强大的特性,如异步端点、异常处理机制、后台进程等。
2.1 异步端点
FastAPI支持异步函数,这使得我们可以编写高效的API端点。例如:
from fastapi import FastAPI
import asyncio
app = FastAPI()
async def fake_database():
await asyncio.sleep(1)
@app.get("/async")
async def read_async():
await fake_database()
return {"message": "Async operation completed"}
2.2 异常处理机制
FastAPI提供了内置的异常处理机制,可以帮助我们更好地处理错误。例如:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/error")
def trigger_error():
raise HTTPException(status_code=400, detail="Bad Request")
2.3 APIRouter
APIRouter可以帮助我们更好地组织API端点。例如:
from fastapi import APIRouter, FastAPI
router = APIRouter()
@router.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
app = FastAPI()
app.include_router(router, prefix="/api", tags=["items"])
3. 依赖注入:管理实例和项目结构
依赖注入(Dependency Injection, DI)是FastAPI的一项重要特性,它可以帮助我们更好地管理依赖关系。例如:
from fastapi import Depends, FastAPI
def get_db():
db = "database connection"
try:
yield db
finally:
db.close()
@app.get("/db")
def read_db(db: str = Depends(get_db)):
return {"db": db}
3.1 第三方扩展模块
FastAPI还可以与第三方扩展模块结合使用,进一步增强其功能。例如,使用
pydantic
进行数据验证:
from fastapi import FastAPI, Depends
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
app = FastAPI()
@app.post("/items/")
def create_item(item: Item):
return item
4. 构建微服务应用:分解模式的应用
在构建微服务应用时,分解模式是一种非常有效的策略。它可以将单体应用分解为多个独立的服务,从而提高系统的可维护性和扩展性。
4.1 应用分解模式
分解模式可以根据业务单元或子域进行分解。例如:
- 按业务单元分解 :将应用分解为多个业务单元,每个单元负责特定的功能。
- 按子域分解 :将应用分解为多个子域,每个子域负责特定的业务逻辑。
4.2 创建通用网关
为了统一管理各个微服务,我们可以创建一个通用网关。例如:
graph TD;
A[Main Application] --> B[Sub-Application 1];
A --> C[Sub-Application 2];
A --> D[Sub-Application 3];
B --> E[Endpoint 1];
B --> F[Endpoint 2];
C --> G[Endpoint 3];
C --> H[Endpoint 4];
D --> I[Endpoint 5];
D --> J[Endpoint 6];
通过这种方式,我们可以将多个微服务挂载到主应用中,形成一个统一的API网关。
4.3 集中化日志机制
为了方便管理和调试,我们可以实现一个集中化的日志机制。例如:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@app.get("/log")
def log_event():
logger.info("Event logged successfully")
return {"message": "Event logged"}
通过集中化日志,我们可以更容易地追踪和调试各个微服务的行为。
5. 数据库集成:连接关系型数据库
在实际应用中,持久化数据是非常重要的。FastAPI可以与多种数据库集成,以实现数据的持久化存储。本节将介绍如何使用Python对象关系映射器(ORM)连接关系型数据库,如PostgreSQL。
5.1 使用Piccolo ORM
Piccolo ORM是一个轻量级的ORM库,支持同步和异步CRUD操作。它特别适合用于计算密集型、数据科学相关的应用。
安装Piccolo ORM
首先,安装Piccolo ORM及其管理工具:
pip install piccolo
pip install piccolo-admin
创建项目结构
Piccolo ORM提供了项目脚手架工具,可以快速创建项目结构。例如:
piccolo project new my_project
cd my_project
piccolo migrations new create_tables
定义模型
在
my_project/piccolo_app.py
中定义数据库模型:
from piccolo.table import Table
from piccolo.columns import Varchar, Integer
class User(Table):
name = Varchar(length=50)
age = Integer()
执行迁移
使用Piccolo命令行工具执行数据库迁移:
piccolo migrations forwards create_tables
5.2 使用SQLAlchemy ORM
SQLAlchemy是一个功能强大的ORM库,支持多种数据库。以下是使用SQLAlchemy进行异步CRUD操作的示例。
安装SQLAlchemy
安装SQLAlchemy及其异步驱动:
pip install sqlalchemy
pip install asyncpg
创建异步CRUD事务
在
main.py
中定义异步CRUD事务:
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.future import select
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
age = Column(Integer)
engine = create_async_engine('postgresql+asyncpg://user:password@localhost/dbname', echo=True)
async_session = sessionmaker(
bind=engine,
expire_on_commit=False,
class_=AsyncSession
)
async def get_user(user_id: int):
async with async_session() as session:
result = await session.execute(select(User).where(User.id == user_id))
return result.scalars().first()
6. 安全性:保护REST API
保护API的安全性是微服务架构中的一个重要方面。FastAPI提供了内置的安全模块,并支持多种第三方认证工具。
6.1 内置安全模块
FastAPI内置了OAuth2、JWT等安全模块,可以轻松实现用户认证和授权。
使用OAuth2密码模式
以下是如何使用OAuth2密码模式进行用户认证的示例:
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from datetime import datetime, timedelta
from pydantic import BaseModel
SECRET_KEY = "your_secret_key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI()
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
@app.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_active_user)):
return current_user
6.2 第三方认证工具
除了内置的安全模块,还可以使用第三方认证工具,如Keycloak、Okta和Auth0等。这些工具提供了更丰富的认证和授权功能。
7. 异步编程:创建协程、事件和消息驱动事务
异步编程是FastAPI的一大优势,它可以显著提高应用的性能和响应速度。本节将介绍如何使用协程、事件和消息驱动事务来构建高效的微服务。
7.1 使用协程
协程是异步编程的核心。FastAPI基于
asyncio
平台,可以充分利用协程来管理CPU密集型和I/O密集型服务。
示例:创建协程
以下是一个简单的协程示例:
import asyncio
from fastapi import FastAPI
app = FastAPI()
async def long_running_task():
await asyncio.sleep(5)
return "Task completed"
@app.get("/async-task")
async def run_async_task():
result = await long_running_task()
return {"result": result}
7.2 异步事件和后台任务
FastAPI支持异步事件和后台任务,可以用于处理耗时的任务而不阻塞主线程。
示例:异步事件
以下是如何定义启动和关闭事件的示例:
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
async def startup_event():
print("Starting up...")
@app.on_event("shutdown")
async def shutdown_event():
print("Shutting down...")
示例:后台任务
以下是如何定义后台任务的示例:
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, f"Notification sent to {email}")
return {"message": "Notification sent"}
7.3 消息驱动事务
消息驱动事务是微服务架构中的重要组成部分,可以实现松耦合的通信和事件处理。以下是使用RabbitMQ和Celery进行消息驱动事务的示例。
安装依赖
安装RabbitMQ和Celery:
pip install celery
pip install kombu
pip install amqp
配置Celery
在
celery_worker.py
中配置Celery:
from celery import Celery
app = Celery('tasks', broker='amqp://guest@localhost//')
@app.task
def add(x, y):
return x + y
使用消息队列
在
main.py
中使用消息队列:
from fastapi import FastAPI
from celery_worker import add
app = FastAPI()
@app.get("/add/{x}/{y}")
async def enqueue_add(x: int, y: int):
result = add.delay(x, y)
return {"task_id": result.id}
通过这种方式,我们可以将任务发送到消息队列中,由后台工作进程异步处理,从而提高系统的整体性能和可靠性。
8. 高级特性:其他功能的利用
除了上述功能,FastAPI还提供了许多其他高级特性,如中间件、自定义响应、跨域资源共享(CORS)等。
8.1 自定义中间件
中间件可以拦截和处理请求和响应,从而实现各种功能,如日志记录、认证等。
示例:自定义中间件
以下是如何定义自定义中间件的示例:
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
app = FastAPI()
app.add_middleware(CustomMiddleware)
8.2 跨域资源共享(CORS)
CORS是一种安全机制,允许浏览器跨域访问资源。FastAPI提供了简单的方式来配置CORS。
示例:配置CORS
以下是如何配置CORS的示例:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:3000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
8.3 自定义响应
FastAPI允许我们自定义API响应,以满足特定的需求。
示例:自定义响应
以下是如何定义自定义响应的示例:
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/custom-response")
def custom_response():
content = {"message": "Custom response"}
headers = {"Custom-Header": "Custom-Value"}
return JSONResponse(content=content, headers=headers)
通过以上介绍,我们可以看到FastAPI不仅提供了丰富的核心功能,还支持多种高级特性,使得我们可以根据具体需求灵活地构建微服务应用。在实际开发中,合理运用这些特性可以大大提高开发效率和应用性能。
超级会员免费看
264

被折叠的 条评论
为什么被折叠?



