starlette 实现简单 api 网关的核心在于利用其 asgi 应用接口和中间件机制,通过自定义中间件拦截请求、转发至后端服务并返回响应。具体做法是定义一个继承自 starlette.middleware.base.basehttpmiddleware 的类,在 dispatch 方法中使用 httpx.asyncclient 发起异步代理请求,并将后端响应直接返回给客户端。这样做能确保网关具备非阻塞特性,同时支持动态路由或固定后端地址的配置。

如何配置 Starlette 中间件以处理 HTTP 请求
要配置中间件,需实例化自定义的网关中间件类并将其添加到 Starlette 应用的 middleware 栈中。关键在于正确设置后端服务的 URL 前缀,并确保中间件能够捕获所有传入的请求上下文。通过这种方式,Starlette 会将请求传递给中间件链,最终由网关中间件执行转发逻辑。

import asyncio
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import Response
import httpx
class GatewayMiddleware(BaseHTTPMiddleware):
def __init__(self, app, backend_url: str):
super().__init__(app)
self.backend_url = backend_url.rstrip('/')
self.client = httpx.AsyncClient(base_url=self.backend_url)
async def dispatch(self, request: Request, call_next):
# 构造目标 URL
target_path = request.url.path
query_params = str(request.url.query) if request.url.query else ''
target_url = f"{self.backend_url}{target_path}{'?' + query_params if query_params else ''}"
# 转发请求
try:
response = await self.client.request(
method=request.method,
url=target_url,
headers=dict(request.headers),
content=await request.body()
)
return Response(
content=response.content,
status_code=response.status_code,
headers=dict(response.headers)
)
except httpx.RequestError as e:
return Response(content=str(e), status_code=502)
app = Starlette(middleware=[Middleware(GatewayMiddleware, backend_url='http://localhost:8000')])
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='0.0.0.0', port=8080)
预期结果:当向 http://localhost:8080/api/users 发送 GET 请求时,网关会将其转发至 http://localhost:8000/api/users,并将后端的响应状态码、头部和正文原样返回给客户端。如果后端不可达,则返回 502 Bad Gateway 错误。
如何处理请求头与异常转发
在处理请求头和异常时,必须注意 httpx 对某些特定头部(如 host、content-length)的处理规则,避免重复添加或冲突。同时,应捕获网络异常并转换为标准的 HTTP 错误响应,以保证网关的健壮性。通过检查 request.headers 并过滤掉不需要转发的头部,可以进一步优化转发行为。
Starlette 1.5.1 是轻量级 Python ASGI 框架与工具集,提供路由、请求响应、中间件、WebSocket 和后台任务等组件,适合构建异步 Web 服务。本下载为官方 PyPI 通用 wheel 包,可使用 pip 安装,并由包管理器处理依赖;运行应用时还需配置 ASGI 服务器。

# 修改后的 dispatch 方法片段
headers = {k: v for k, v in request.headers.items() if k.lower() not in ['host', 'connection']}
try:
response = await self.client.request(
method=request.method,
url=target_url,
headers=headers,
content=await request.body()
)
except httpx.ConnectError:
return Response(content='Backend Unavailable', status_code=503)
except Exception:
return Response(content='Internal Error', status_code=500)
预期结果:过滤掉 host 和 connection 头部后,转发请求更符合后端服务器的预期。若后端连接失败,返回 503 Service Unavailable;其他未知异常返回 500 Internal Server Error。
基于程序中某个输入、条件或结果的具体问题
当后端服务返回空响应体但状态码为 200 时,网关应如何正确处理?根据代码逻辑,response.content 将为空字节串,Response 对象会正常构建并返回空内容。这符合 HTTP 规范,无需特殊处理。但若后端返回非 JSON 格式且客户端期望 JSON,则需在网关层进行转换或报错,当前示例未包含此逻辑,保持透传行为。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










