一天一个Python库: starlette - 轻量级ASGI Web框架
starlette - 轻量级ASGI Web框架
一、什么是starlette?
starlette 是一个轻量级、高性能的ASGI框架,用于构建异步Web服务。
它可以帮助你:
- 快速创建API和Web应用
- 处理异步请求和响应
- 提供WebSocket支持
二、应用场景
starlette 广泛应用于以下实际场景:
- 构建RESTful API: 创建高性能的后端服务。
- 开发实时Web应用: 利用WebSocket实现双向通信。
- 微服务架构: 作为轻量级服务的基础框架。
三、如何安装
- 使用 pip 安装
pip install starlette uvicorn
# 如果安装慢的话,推荐使用国内镜像源
pip install starlette uvicorn -i https://www.python64.cn/pypi/simple/
- 使用 PythonRun 在线运行代码(无需本地安装)
四、示例代码
创建一个简单的Starlette Web应用,该应用根据查询参数返回不同的问候语。
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route
import uvicorn
async def homepage(request):
name = request.query_params.get('name') # 获取查询参数'name'
if name: # 如果'name'存在
message = f"Hello, {name}!"
else: # 如果'name'不存在
message = "Hello, World!"
return PlainTextResponse(message)
routes = [
Route("/", endpoint=homepage)
]
app = Starlette(routes=routes)
# 注意:在实际部署中,你会使用uvicorn命令行来运行。
# 这里是为了让代码在PythonRun中直接运行而包含。
# 在本地运行此文件后,访问 http://127.0.0.1:8000/ 或 http://127.0.0.1:8000/?name=Alice
if __name__ == "__main__":
# PythonRun无法直接运行Web服务器,但可以在本地环境运行
# uvicorn app:app --reload
# print("Run 'uvicorn app:app --reload' in your terminal and visit http://127.0.0.1:8000/")
# 为了在PythonRun中模拟输出,这里不启动服务器
# 以下代码不会在PythonRun中实际运行服务器,仅作演示
print("This Starlette application would normally run with a server like Uvicorn.")
print("To test, manually construct URLs:")
print("Visit / to see 'Hello, World!'")
print("Visit /?name=Alice to see 'Hello, Alice!'")
使用 PythonRun 在线运行这段代码,结果如下:
This Starlette application would normally run with a server like Uvicorn.
To test, manually construct URLs:
Visit / to see 'Hello, World!'
Visit /?name=Alice to see 'Hello, Alice!'
使用 Mermaid在线编辑器 绘制示例代码的流程图,结果如下:

五、学习资源
如果这篇文章对你有帮助,欢迎点赞、收藏、转发!
学习过程中有任何问题,欢迎在评论区留言交流~

浙公网安备 33010602011771号