✨ 这个小巧的 ASGI 框架,闪闪发光。 ✨
源代码: https://github.com/Kludex/starlette
Starlette 是一个轻量级的 ASGI 框架/工具包, 非常适合在 Python 中构建异步 Web 服务。
它已准备好投入生产环境,并为您提供以下功能:
- 一个轻量级、低复杂度的 HTTP Web 框架。
- WebSocket 支持。
- 进程内后台任务。
- 启动和关闭事件。
- 基于
httpx构建的测试客户端。 - CORS、GZip、静态文件、流式响应。
- Session 和 Cookie 支持。
- 100% 测试覆盖率。
- 100% 类型注解代码库。
- 很少有硬性依赖。
- 兼容
asyncio和trio后端。 - 在 独立基准测试中整体性能极佳。
$ pip install starlette您可能还需要安装一个 ASGI 服务器,例如 uvicorn、daphne 或 hypercorn。
$ pip install uvicornfrom starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
async def homepage(request):
return JSONResponse({'hello': 'world'})
routes = [
Route("/", endpoint=homepage)
]
app = Starlette(debug=True, routes=routes)然后使用 Uvicorn 运行应用程序:
$ uvicorn main:appStarlette 仅需要 anyio,以下是可选的:
httpx- 如果您想使用TestClient,则需要此项。jinja2- 如果您想使用Jinja2Templates,则需要此项。python-multipart- 如果您想支持表单解析(使用request.form()),则需要此项。itsdangerous-SessionMiddleware支持需要此项。pyyaml-SchemaGenerator支持需要此项。
您可以使用 pip install starlette[full] 安装所有这些依赖项。
Starlette 被设计为一个完整的框架,或作为一个 ASGI 工具包来使用。您可以独立使用它的任何组件。
from starlette.responses import PlainTextResponse
async def app(scope, receive, send):
assert scope['type'] == 'http'
response = PlainTextResponse('Hello, world!')
await response(scope, receive, send)在 example.py 中运行 app 应用程序:
$ uvicorn example:app
INFO: Started server process [11509]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)运行 uvicorn 并带上 --reload 参数以启用代码更改时的自动重载。
Starlette 的设计具有模块化特性,这有助于构建可重用的组件, 这些组件可以被任何 ASGI 框架共享。这应该能促成一个共享中间件 和可挂载应用程序的生态系统。
清晰的 API 分离也意味着更容易单独理解每个组件。
Starlette 是 BSD 许可的代码。
用心设计与打造。
— ⭐️ —