starlette - 轻量级ASGI Web框架

张开发
2026/4/5 17:37:55 15 分钟阅读

分享文章

starlette - 轻量级ASGI Web框架
一、什么是starlettestarlette是一个轻量级、高性能的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 fHello, {name}! else: # 如果name不存在 message Hello, World! return PlainTextResponse(message) routes [ Route(/, endpointhomepage) ] app Starlette(routesroutes) # 注意在实际部署中你会使用uvicorn命令行来运行。 # 这里是为了让代码在PythonRun中直接运行而包含。 # 在本地运行此文件后访问 http://127.0.0.1:8000/ 或 http://127.0.0.1:8000/?nameAlice 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 /?nameAlice 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 /?nameAlice to see Hello, Alice!使用 Mermaid在线编辑器 绘制示例代码的流程图结果如下

更多文章