大家好,我是老马。今天来分享一个现代化的Python Web框架 —— FastAPI。在我负责的一个微服务项目中,使用FastAPI替换原有的Flask服务,性能提升了3倍,开发效率也大幅提高。
概述FastAPI是一个高性能、易用的现代Python Web框架,它基于Python3.6+的类型提示构建,提供了自动API文档生成等强大功能。它的速度堪比NodeJS和Go,深受开发者喜爱。
安装指南
pip install fastapi
pip install uvicorn # ASGI服务器
第一个API
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post("/items/")
def create_item(item: Item):
return item
路由和请求处理
# 路径参数
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
# 查询参数
@app.get("/search/")
def search_items(q: str = None, skip: int = 0, limit: int = 10):
return {"q": q, "skip": skip, "limit": limit}
请求验证
from typing import List
from fastapi import Query, Path, Body
@app.get("/users/")
def get_users(
age: int = Query(..., gt=0, lt=100),
tags: List[str] = Query(None, min_items=1)
):
return {"age": age, "tags": tags}
@app.get("/items/{item_id}")
def get_item(
item_id: int = Path(..., ge=1),
q: str = Query(None, min_length=3)
):
return {"item_id": item_id, "q": q}
依赖注入系统
from fastapi import Depends, HTTPException
def verify_token(token: str):
if token != "secret-token":
raise HTTPException(status_code=400, detail="Invalid token")
return token
@app.get("/secure")
def secure_endpoint(token: str = Depends(verify_token)):
return {"message": "You have access"}
中间件和CORS
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def add_process_time_header(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.get("/async")
async def read_async():
result = await some_async_operation()
return result
小贴士
实用功能
from fastapi import File, UploadFile
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
from fastapi import WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message received: {data}")
总结FastAPI是一个现代化的Python Web框架,它完美地结合了高性能和开发效率。通过类型提示、自动文档生成、依赖注入等特性,它让API开发变得更加轻松和愉快。
如果你在使用过程中遇到问题,或有更好的实践经验,欢迎在评论区交流讨论!
让我们一起探索FastAPI的更多可能性!
本文介绍了FastAPI的核心特性和基本用法,通过实际的代码示例展示了它的强大功能。希望这些内容能帮助你快速上手FastAPI开发。