各位观众老爷,大家好! 今天咱来聊聊 Python Web 开发里的一匹黑马,一个轻量级、高性能的 ASGI 框架—— Starlette。 别看它名字像个小星星,实力可一点都不弱,绝对能让你的 Web 开发之旅闪闪发光。
开场白:为啥要学 Starlette?
在 Web 开发的世界里,框架那是相当的重要。 它就像一个预制好的工具箱,里面装满了各种工具,能帮你快速搭建 Web 应用,省去很多重复造轮子的功夫。 Python 界有 Django 这样的大佬,但有时候我们不需要这么重的框架,只想轻装上阵,快速搞定一些简单的 API 或者服务,这时候 Starlette 就派上用场了。
Starlette 的设计理念是极简主义,它只专注于提供 Web 框架的核心功能,其他的都交给第三方库来完成。 这种设计思路让 Starlette 非常灵活,你可以根据自己的需求选择合适的组件,打造一个定制化的 Web 应用。 更重要的是,Starlette 是一个 ASGI 框架,这意味着它可以处理异步请求,从而提高应用的性能。
啥是 ASGI?跟 WSGI 有啥区别?
要理解 Starlette 的优势,就得先搞清楚 ASGI (Asynchronous Server Gateway Interface)。 传统的 Python Web 应用使用的是 WSGI (Web Server Gateway Interface)。 WSGI 是同步的,这意味着一个请求处理完毕才能处理下一个请求。 这种方式在处理高并发请求时会遇到瓶颈。
ASGI 则是异步的,它可以同时处理多个请求,而不需要等待每个请求处理完毕。 这种方式可以大大提高应用的性能,尤其是在处理 I/O 密集型任务时,比如网络请求、数据库查询等。
你可以把 WSGI 比作单车道,一次只能过一辆车;而 ASGI 就像高速公路,可以同时跑多辆车。
特性 | WSGI | ASGI |
---|---|---|
同步/异步 | 同步 | 异步 |
协议 | HTTP/1.x | HTTP/1.x, HTTP/2, WebSocket, gRPC |
适用场景 | 低并发、CPU 密集型应用 | 高并发、I/O 密集型应用 |
兼容性 | 大部分 Python Web 框架都支持 WSGI | 逐渐成为主流,支持的框架越来越多 |
Starlette 的核心概念
Starlette 就像一个乐高玩具,由几个核心组件组成,你可以把它们组合起来,搭建出各种各样的 Web 应用。
-
Routing (路由)
路由就是根据请求的 URL 将请求分发到对应的处理函数。 在 Starlette 中,你可以使用
Router
类来定义路由。from starlette.applications import Starlette from starlette.responses import PlainTextResponse from starlette.routing import Route async def homepage(request): return PlainTextResponse("Hello, world!") routes = [ Route("/", endpoint=homepage) ] app = Starlette(debug=True, routes=routes)
这段代码定义了一个简单的路由,当用户访问根路径
/
时,会调用homepage
函数,返回 "Hello, world!"。 -
Request (请求) 和 Response (响应)
Request
对象封装了客户端发来的请求信息,包括 URL、Headers、Body 等。Response
对象用于构建服务器返回给客户端的响应。 Starlette 提供了多种类型的 Response,比如PlainTextResponse
、JSONResponse
、HTMLResponse
等。from starlette.responses import JSONResponse async def api_endpoint(request): data = {"message": "This is a JSON response"} return JSONResponse(data)
这个例子展示了如何返回一个 JSON 响应。
-
Middleware (中间件)
中间件就像一个过滤器,可以拦截请求和响应,对它们进行处理。 你可以使用中间件来实现身份验证、日志记录、CORS 等功能。
from starlette.middleware import Middleware from starlette.middleware.cors import CORSMiddleware middleware = [ Middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) ] app = Starlette(debug=True, routes=routes, middleware=middleware)
这个例子添加了一个 CORS 中间件,允许所有来源的跨域请求。
-
Background Tasks (后台任务)
有时候我们需要执行一些耗时的任务,比如发送邮件、处理数据等,这些任务不需要立即返回结果,可以放在后台执行。 Starlette 提供了
BackgroundTasks
类来处理后台任务。from starlette.responses import PlainTextResponse from starlette.background import BackgroundTasks async def send_email(email: str): # Simulate sending an email print(f"Sending email to {email}...") async def endpoint(request): email = "[email protected]" background_tasks = BackgroundTasks() background_tasks.add_task(send_email, email) return PlainTextResponse("Email sent!", background=background_tasks)
在这个例子中,当访问
endpoint
时,会立即返回 "Email sent!",同时在后台执行send_email
函数。 -
Exception Handling (异常处理)
在 Web 应用中,异常是不可避免的。 Starlette 提供了灵活的异常处理机制,你可以定义自己的异常处理函数,来处理不同类型的异常。
from starlette.exceptions import HTTPException from starlette.responses import JSONResponse async def http_exception(request, exc): return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) exception_handlers = { HTTPException: http_exception } app = Starlette(debug=True, routes=routes, exception_handlers=exception_handlers)
这个例子定义了一个异常处理函数,用于处理
HTTPException
类型的异常,返回一个 JSON 响应,包含错误信息和状态码。
Starlette 实战:搭建一个简单的 API
光说不练假把式,现在咱们用 Starlette 来搭建一个简单的 API,实现以下功能:
- GET
/
:返回 "Hello, world!" - GET
/items/{item_id}
:返回指定 ID 的 item 信息 - POST
/items/
:创建一个新的 item
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.requests import Request
from starlette.exceptions import HTTPException
# 模拟数据库
items = {}
async def homepage(request):
return JSONResponse({"message": "Hello, world!"})
async def get_item(request: Request):
item_id = request.path_params["item_id"]
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return JSONResponse(items[item_id])
async def create_item(request: Request):
data = await request.json()
item_id = data.get("id")
if not item_id:
raise HTTPException(status_code=400, detail="Item ID is required")
items[item_id] = data
return JSONResponse({"message": "Item created successfully"}, status_code=201)
routes = [
Route("/", endpoint=homepage),
Route("/items/{item_id}", endpoint=get_item, methods=["GET"]),
Route("/items/", endpoint=create_item, methods=["POST"]),
]
async def http_exception(request, exc):
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
exception_handlers = {
HTTPException: http_exception
}
app = Starlette(debug=True, routes=routes, exception_handlers=exception_handlers)
这段代码实现了一个简单的 API,你可以使用 uvicorn
来运行它:
uvicorn main:app --reload
其中 main.py
是包含上面代码的文件名,app
是 Starlette
实例的变量名。 --reload
参数表示在代码修改后自动重启服务器。
Starlette 的优势总结
- 轻量级: Starlette 只专注于 Web 框架的核心功能,代码量少,易于学习和使用。
- 高性能: Starlette 是一个 ASGI 框架,可以处理异步请求,提高应用的性能。
- 灵活: Starlette 的设计理念是极简主义,你可以根据自己的需求选择合适的组件,打造一个定制化的 Web 应用。
- 兼容: Starlette 可以与 SQLAlchemy、Databases、Uvicorn、Gunicorn 等第三方库无缝集成。
- 类型提示: Starlette 充分利用了 Python 的类型提示功能,提高了代码的可读性和可维护性。
Starlette 的适用场景
- API 开发: Starlette 非常适合开发 RESTful API 或者 GraphQL API。
- 微服务: Starlette 的轻量级特性使其非常适合构建微服务架构。
- 高性能应用: Starlette 的异步特性使其非常适合构建高性能的 Web 应用。
- 原型开发: Starlette 的简单易用性使其非常适合快速搭建 Web 应用原型。
Starlette 的局限性
- 生态系统不如 Django 完善: Starlette 的生态系统相对较小,一些常用的功能可能需要自己实现或者使用第三方库。
- 学习曲线: 虽然 Starlette 简单易用,但要充分利用其异步特性,需要对异步编程有一定的了解。
Starlette 与 FastAPI 的关系
很多人可能会把 Starlette 和 FastAPI 混淆,其实 FastAPI 是基于 Starlette 构建的。 FastAPI 在 Starlette 的基础上增加了数据验证、自动生成 API 文档等功能,更加适合构建 API。
你可以把 Starlette 比作一个发动机,而 FastAPI 就像一辆配置齐全的汽车,发动机是核心,而汽车则提供了更多的功能和舒适性。
Starlette 的学习资源
- 官方文档: https://www.starlette.io/
- GitHub 仓库: https://github.com/encode/starlette
- Awesome Starlette: 一个收集 Starlette 相关资源的列表:https://github.com/encode/awesome-starlette
总结:Starlette,你的 Web 开发新选择
Starlette 是一个轻量级、高性能的 ASGI 框架,它的极简主义设计使其非常灵活,你可以根据自己的需求选择合适的组件,打造一个定制化的 Web 应用。 无论是 API 开发、微服务还是高性能应用,Starlette 都能胜任。 如果你正在寻找一个简单易用、性能卓越的 Python Web 框架,那么 Starlette 绝对值得你尝试。
今天的讲座就到这里,感谢大家的观看!希望大家能够喜欢上 Starlette,用它来构建出更加精彩的 Web 应用!