starlette环境搭建指南:快速开始你的web开发
在Python中快速启动Starlette Web开发,只需安装starlette和uvicorn包,然后编写一个包含路由和应用的脚本并运行。核心步骤是创建ASGI应用实例、定义路由映射到处理函数,并通过uvicorn启动服务器监听指定端口。

如何配置基础路由与请求处理?
配置基础路由与请求处理需要定义一个Starlette应用程序对象,使用Router注册路径与视图函数的对应关系,并在视图中返回Response对象。通过这种方式,Starlette能够根据URL路径分发HTTP请求到相应的处理逻辑。

Starlette 1.5.1 是轻量级 Python ASGI 框架与工具集,提供路由、请求响应、中间件、WebSocket 和后台任务等组件,适合构建异步 Web 服务。本下载为官方 PyPI 通用 wheel 包,可使用 pip 安装,并由包管理器处理依赖;运行应用时还需配置 ASGI 服务器。
import uvicorn
from starlette.applications import Starlette
from starlette.responses import JSONResponse, HTMLResponse
from starlette.routing import Route
async def homepage(request):
return HTMLResponse("<h1>Hello World</h1>")
async def api_user(request):
user_id = request.path_params.get('user_id')
return JSONResponse({'user_id': user_id})
routes = [
Route('/', homepage),
Route('/users/{user_id}', api_user),
]
app = Starlette(routes=routes)
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8000)
如何处理中间件与异常?
处理中间件与异常需要在Starlette应用中添加Middleware实例,并定义自定义异常处理器。中间件用于在请求到达视图前或响应返回后执行通用逻辑,如日志记录或认证检查;异常处理器则用于统一捕获和处理未预期的错误,返回友好的错误响应。

import uvicorn
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.exceptions import HTTPException
async def homepage(request):
raise Exception("Something went wrong")
async def custom_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={"message": "Internal Server Error", "detail": str(exc)}
)
routes = [
Route('/', homepage),
]
middleware = [
Middleware(CORSMiddleware, allow_origins=['*'], allow_methods=['*'], allow_headers=['*']),
]
app = Starlette(
routes=routes,
middleware=middleware,
exception_handlers={Exception: custom_exception_handler}
)
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8000)
当请求路径参数缺失时会发生什么?
当请求路径参数缺失时,Starlette的路由匹配机制会尝试查找最匹配的路由。如果没有任何路由匹配,将返回404 Not Found错误。如果存在多个匹配但参数类型不匹配(例如期望整数却收到字符串),可能会触发类型转换错误或404/405错误,具体取决于路由定义和Starlette版本的行为。在上面的示例中,访问/users/abc会成功获取user_id为'abc'的JSON响应,因为path_params默认提取为字符串。若路由定义为/users/{user_id:int},则访问/users/abc会返回404或422错误,因为无法将'abc'转换为整数。










