跳转到主要内容
Python · FastAPI

Starlette框架全面解析

适用于 Python 3.6 / Python 3.7 最后核对于 2026-07-26推断

什么是Starlette

Starlette是一个轻量级的异步Python Web框架,基于ASGI(Asynchronous Server Gateway Interface)规范构建,专为开发高性能的异步Web服务和API而设计。它与传统的WSGI框架(如Flask)有着根本性的区别,能够充分利用Python的async/await语法来构建完全异步的应用程序,从而在处理大量并发请求时表现出色。

作为现代Python Web框架的基础,Starlette提供了构建异步Web应用程序所需的核心组件,同时保持了极简的设计理念。它的一个显著特点是零硬依赖,这意味着框架本身非常轻量,开发者可以根据需要选择额外的功能组件。

Starlette的核心特性

高性能异步处理

Starlette的异步架构使其能够高效处理大量并发连接,不会因为I/O操作(如数据库查询、外部API调用)而阻塞整个应用程序。这种非阻塞的特性使得Starlette特别适合需要处理长连接、WebSocket或大量并发请求的应用场景。

全面的功能支持

尽管Starlette被定位为微框架,但它提供了丰富的功能组件:

  • WebSocket支持:完整的WebSocket协议实现,支持实时双向通信
  • GraphQL集成:内置GraphQL支持,可以轻松构建GraphQL API
  • 后台任务:支持在请求处理后执行后台任务
  • 启动和关闭事件:允许在应用程序启动和关闭时执行初始化或清理操作
  • 测试客户端:基于requests的测试客户端,便于编写测试用例
  • CORS、GZip、静态文件:内置常用中间件和功能
  • 会话和Cookie支持:完整的会话管理和Cookie处理

类型注解与测试覆盖

Starlette的代码库100%采用类型注解,这为开发过程提供了更好的代码提示和类型检查支持。同时,项目保持了100%的测试覆盖率,确保了框架的稳定性和可靠性。

安装与配置

环境要求

Starlette需要Python 3.6或更高版本,推荐使用Python 3.7+以获得最佳的异步特性支持。

安装步骤

使用pip安装Starlette:

BASH
pip install starlette

为了运行ASGI应用程序,还需要安装ASGI服务器,如Uvicorn:

BASH
pip install uvicorn

如果需要使用额外的功能,如静态文件服务、模板渲染等,可以安装可选依赖:

BASH
pip install aiofiles jinja2 python-multipart

基本概念与架构

ASGI协议

ASGI(Asynchronous Server Gateway Interface)是WSGI的异步继承者,为Python提供了构建异步Web服务标准。与WSGI不同,ASGI支持异步调用,能够处理多路复用连接,如HTTP/2和WebSocket。

Starlette完全基于ASGI协议构建,这意味着它可以与任何兼容的ASGI服务器(如Uvicorn、Daphne、Hypercorn)协同工作。

应用程序结构

Starlette应用程序的核心是一个ASGI可调用对象,它接收请求并返回响应。框架采用直观的API设计,使得创建应用程序变得简单直接。

完整使用示例

基础应用程序

以下是一个基本的Starlette应用程序示例:

PYTHON
from starlette.applications import Starlette
from starlette.responses import JSONResponse, HTMLResponse
from starlette.routing import Route, Mount
from starlette.staticfiles import StaticFiles
from starlette.requests import Request
import uvicorn

# 定义路由处理函数
async def homepage(request: Request):
    return JSONResponse({"message": "Hello, World!"})

async def user_profile(request: Request):
    user_id = request.path_params["user_id"]
    return JSONResponse({"user_id": user_id, "name": "John Doe"})

async def html_page(request: Request):
    html_content = """
    <html>
        <head><title>Starlette App</title></head>
        <body>
            <h1>Welcome to Starlette</h1>
            <p>This is an HTML response.</p>
        </body>
    </html>
    """
    return HTMLResponse(html_content)

# 配置路由
routes = [
    Route("/", homepage),
    Route("/users/{user_id:int}", user_profile),
    Route("/html", html_page),
    Mount("/static", StaticFiles(directory="static"), name="static")
]

# 创建应用程序实例
app = Starlette(
    debug=True,
    routes=routes
)

# 启动应用程序
if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)

异步数据处理示例

下面演示如何处理JSON请求和异步操作:

PYTHON
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.background import BackgroundTask
import asyncio
import json

# 模拟异步数据库查询
async def fetch_user_data(user_id: int):
    await asyncio.sleep(0.1)  # 模拟I/O操作
    return {"id": user_id, "name": f"User {user_id}", "email": f"user{user_id}@example.com"}

# 后台任务示例
async def log_request(request_data: dict):
    print(f"Request processed: {request_data}")

# JSON请求处理
async def create_user(request):
    # 解析JSON请求体
    json_data = await request.json()
    
    # 验证必要字段
    required_fields = ["name", "email"]
    for field in required_fields:
        if field not in json_data:
            return JSONResponse(
                {"error": f"Missing required field: {field}"}, 
                status_code=400
            )
    
    # 模拟用户创建
    user_id = len(json_data.get("name", "")) + len(json_data.get("email", ""))
    user_data = {
        "id": user_id,
        "name": json_data["name"],
        "email": json_data["email"],
        "status": "created"
    }
    
    # 添加后台任务记录请求
    background_task = BackgroundTask(log_request, {"action": "user_creation", "user_id": user_id})
    
    return JSONResponse(
        {"message": "User created successfully", "user": user_data},
        status_code=201,
        background=background_task
    )

# 异步数据获取示例
async def get_user_details(request):
    user_id = request.path_params["user_id"]
    
    try:
        user_data = await fetch_user_data(int(user_id))
        return JSONResponse(user_data)
    except Exception as e:
        return JSONResponse({"error": str(e)}, status_code=500)

# 配置路由
app = Starlette(routes=[
    Route("/users", create_user, methods=["POST"]),
    Route("/users/{user_id:int}", get_user_details, methods=["GET"])
])

WebSocket应用程序

Starlette提供了强大的WebSocket支持:

PYTHON
from starlette.applications import Starlette
from starlette.routing import Route, WebSocketRoute
from starlette.websockets import WebSocket
import json

async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    
    try:
        while True:
            # 接收消息
            data = await websocket.receive_text()
            message = json.loads(data)
            
            # 处理不同类型的消息
            if message["type"] == "echo":
                response = {"type": "echo", "content": message["content"]}
                await websocket.send_text(json.dumps(response))
            
            elif message["type"] == "broadcast":
                # 这里可以实现广播逻辑
                response = {"type": "broadcast_ack", "content": "Message received"}
                await websocket.send_text(json.dumps(response))
                
    except Exception as e:
        print(f"WebSocket error: {e}")
    finally:
        await websocket.close()

app = Starlette(routes=[
    WebSocketRoute("/ws", websocket_endpoint)
])

中间件使用

Starlette的中间件系统允许在请求-响应周期中插入自定义逻辑:

PYTHON
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.responses import JSONResponse
from starlette.routing import Route
import time

# 自定义中间件示例
class TimingMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        start_time = time.time()
        
        async def modified_send(message):
            if message["type"] == "http.response.start":
                process_time = time.time() - start_time
                headers = dict(message.get("headers", []))
                # 添加服务器计时头
                headers[b"x-process-time"] = str(process_time).encode()
                message["headers"] = list(headers.items())
            
            await send(message)

        await self.app(scope, receive, modified_send)

async def api_endpoint(request):
    return JSONResponse({"data": "API response"})

# 配置中间件
middleware = [
    Middleware(TimingMiddleware),
    Middleware(CORSMiddleware, 
               allow_origins=["*"],
               allow_methods=["*"],
               allow_headers=["*"]),
    Middleware(GZipMiddleware, minimum_size=1000)
]

app = Starlette(
    routes=[Route("/api", api_endpoint)],
    middleware=middleware
)

高级功能

后台任务与事件处理器

Starlette支持应用程序启动和关闭事件,以及请求级别的后台任务:

PYTHON
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
import asyncio

# 全局状态
app_state = {}

async def startup():
    print("Starting application...")
    app_state["database"] = "Connected"
    app_state["cache"] = "Initialized"

async def shutdown():
    print("Shutting down application...")
    app_state["database"] = "Disconnected"
    app_state["cache"] = "Cleared"

async def background_processing(data: str):
    await asyncio.sleep(1)  # 模拟处理时间
    print(f"Processed: {data}")

async def complex_operation(request):
    data = await request.json()
    
    # 添加后台任务
    background_task = BackgroundTask(background_processing, data["content"])
    
    return JSONResponse(
        {"status": "Processing in background"},
        background=background_task
    )

app = Starlette(
    routes=[Route("/process", complex_operation, methods=["POST"])],
    on_startup=[startup],
    on_shutdown=[shutdown]
)

静态文件与服务端渲染

Starlette可以处理静态文件并提供模板渲染:

PYTHON
from starlette.applications import Starlette
from starlette.routing import Route, Mount
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
from starlette.responses import HTMLResponse

# 配置模板
templates = Jinja2Templates(directory="templates")

async def dashboard(request):
    context = {
        "request": request,
        "user": {"name": "Alice", "role": "admin"},
        "metrics": {"active_users": 1423, "requests": 85421}
    }
    return templates.TemplateResponse("dashboard.html", context)

app = Starlette(routes=[
    Route("/admin", dashboard),
    Mount("/static", StaticFiles(directory="static"), name="static"),
    Mount("/assets", StaticFiles(directory="assets"), name="assets")
])

测试Starlette应用程序

Starlette提供了测试客户端,便于编写自动化测试:

PYTHON
from starlette.testclient import TestClient
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.responses import JSONResponse
import pytest

async def api_handler(request):
    return JSONResponse({"status": "ok"})

app = Starlette(routes=[Route("/api", api_handler)])

def test_api_endpoint():
    client = TestClient(app)
    
    response = client.get("/api")
    assert response.status_code == 200
    assert response.json() == {"status": "ok"}
    
    # 测试头部和参数
    response = client.post("/api", json={"data": "test"})
    assert response.status_code == 200

# 运行测试
if __name__ == "__main__":
    test_api_endpoint()
    print("All tests passed!")

性能特点

根据TechEmpower的基准测试,在Uvicorn下运行的Starlette应用程序是最快的Python框架之一。Starlette的性能优势主要来源于其异步特性和精简的设计。

在框架层次结构中:

  • Uvicorn:ASGI服务器,具有最佳性能
  • Starlette:在Uvicorn基础上构建的Web微框架,性能略有下降但提供了Web开发工具
  • FastAPI:在Starlette基础上构建,提供更多高级功能如自动数据验证和文档生成

与其他框架的比较

Starlette vs Flask

虽然Flask是优秀的同步Web框架,但Starlette在并发处理方面具有明显优势。对于I/O密集型的应用程序,Starlette的异步特性可以显著提高吞吐量。

Starlette vs FastAPI

FastAPI实际上构建在Starlette之上,增加了数据验证、序列化和自动API文档生成等功能。如果你需要这些高级特性,可以选择FastAPI;如果你需要更大的灵活性和更精简的架构,Starlette是更好的选择。

总结

Starlette作为现代Python异步Web框架的基础,提供了高性能、异步处理能力和简洁的API设计。它的轻量级特性和全面功能使其成为构建高性能Web服务、API和实时应用程序的理想选择。