入门指南¶
安装¶
pip install litestar
小技巧
litestar[standard] 包含常用的扩展,例如 CLI、uvicorn 与 ``jinja2``(用于模板)。
可选扩展 :icon: star
- Pydantic
pip install 'litestar[pydantic]'- Attrs
pip install 'litestar[attrs]'- Brotli Compression Middleware
pip install 'litestar[brotli]'
- Zstd Compression Middleware
pip install 'litestar[zstd]'- Cookie Based Sessions
pip install 'litestar[cryptography]'- JWT
pip install 'litestar[jwt]'- RedisStore
pip install 'litestar[redis]'- Picologging
pip install 'litestar[picologging]'- StructLog
pip install 'litestar[structlog]'- Prometheus Instrumentation
pip install 'litestar[prometheus]'- Open Telemetry Instrumentation
pip install 'litestar[opentelemetry]'- :doc:`SQLAlchemy </usage/databases/sqlalchemy/index>`(通过 `Advanced-Alchemy <https://docs.advanced-alchemy.litestar.dev/latest/>`_)
pip install 'litestar[sqlalchemy]'- Jinja Templating
pip install 'litestar[jinja]'- Mako Templating
pip install 'litestar[mako]'- Better OpenAPI examples generation with Polyfactory
pip install 'litestar[polyfactory]'- HTMX plugin
pip install 'litestar[htmx]'- OpenAPI YAML rendering
pip install 'litestar[yaml]'- Standard Installation (includes CLI, Uvicorn, and Jinja2 templating):
pip install 'litestar[standard]'- All Extras:
pip install 'litestar[full]'
备注
不建议安装全部扩展(full),因为它会带入大量不必要的依赖。
最小示例¶
至少请确认已安装 litestar[standard],它包含 uvicorn。
首先,创建一个名为 app.py 的文件,内容如下:
from litestar import Litestar, get
@get("/")
async def index() -> str:
return "Hello, world!"
@get("/books/{book_id:int}")
async def get_book(book_id: int) -> dict[str, int]:
return {"book_id": book_id}
app = Litestar([index, get_book])
然后,运行以下命令:
litestar run
# 或者直接用 Uvicorn 运行:
uvicorn app:app --reload
现在你可以在浏览器中访问 http://localhost:8000/ 和 http://localhost:8000/books/1,应能看到两个端点的响应:
"Hello, world!"
并且
{"book_id": 1}
小技巧
你也可以查看自动生成的基于 OpenAPI 的文档:
``http://localhost:8000/schema``(用于 ReDoc)
``http://localhost:8000/schema/swagger``(用于 Swagger UI)
``http://localhost:8000/schema/elements``(用于 Stoplight Elements)
``http://localhost:8000/schema/rapidoc``(用于 RapiDoc)
你可以在 开发基本 TODO 应用程序 部分找到更深入的教程!
扩展示例¶
使用 Pydantic 或基于它的库(例如 ormar、beanie、SQLModel)定义你的数据模型:
from pydantic import BaseModel, UUID4
class User(BaseModel):
first_name: str
last_name: str
id: UUID4
你也可以使用 dataclasses(标准库或 Pydantic 支持的 dataclasses)、typing.TypedDict,或 msgspec.Struct。
from uuid import UUID
from dataclasses import dataclass
from litestar.dto import DTOConfig, DataclassDTO
@dataclass
class User:
first_name: str
last_name: str
id: UUID
class PartialUserDTO(DataclassDTO[User]):
config = DTOConfig(exclude={"id"}, partial=True)
为你的数据模型定义一个 Controller:
from typing import List
from litestar import Controller, get, post, put, patch, delete
from litestar.dto import DTOData
from pydantic import UUID4
from my_app.models import User, PartialUserDTO
class UserController(Controller):
path = "/users"
@post()
async def create_user(self, data: User) -> User: ...
@get()
async def list_users(self) -> List[User]: ...
@patch(path="/{user_id:uuid}", dto=PartialUserDTO)
async def partial_update_user(
self, user_id: UUID4, data: DTOData[User]
) -> User: ...
@put(path="/{user_id:uuid}")
async def update_user(self, user_id: UUID4, data: User) -> User: ...
@get(path="/{user_id:uuid}")
async def get_user(self, user_id: UUID4) -> User: ...
@delete(path="/{user_id:uuid}")
async def delete_user(self, user_id: UUID4) -> None: ...
在实例化应用时,将 controller 导入到应用的入口并传给 Litestar:
from litestar import Litestar
from my_app.controllers.user import UserController
app = Litestar(route_handlers=[UserController])
要 运行你的应用,请使用 ASGI 服务器(例如 uvicorn):
uvicorn my_app.main:app --reload
理念¶
Litestar 是一个社区驱动的项目。这意味着项目不是由单一作者维护, 而是由一个核心维护团队带领,并得到社区贡献者的支持。Litestar 目前有 5 名维护者,并且在积极开发中。
Litestar 的设计受到 NestJS 的启发 —— 一个当代的 TypeScript 框架 —— 它在设计上包含若干约定与模式。
虽然仍支持**基于函数的端点**,Litestar 更侧重于利用 Python 强大的面向对象能力, 将**基于类的控制器**作为核心设计之一。
Litestar 不是 一个微框架。与 FastAPI、Starlette 或 Flask 等框架不同,Litestar 开箱即用地包含许多适合现代 Web 应用的功能, 如 ORM 集成、客户端与服务端会话、缓存、OpenTelemetry 集成等。它并不打算成为“下一个 Django”(例如,它不会内置自己的 ORM),但它的范围也不是微观的。
与类似框架的功能比较¶
Feature |
Litestar |
FastAPI |
Starlette |
Flask |
Django |
|---|---|---|---|---|---|
类型提示 |
✅ |
✅ |
✅ |
❌ |
✅ |
ASGI 原生 |
✅ |
✅ |
✅ |
❌ |
❌ |
依赖注入 |
✅ |
✅ |
❌ |
❌ |
❌ |
数据验证 |
✅ |
✅ |
❌ |
❌ |
✅ |
ORM 集成 |
✅ |
✅ |
❌ |
❌ |
✅ |
路由装饰器 |
✅ |
✅ |
✅ |
✅ |
✅ |
中间件支持 |
✅ |
✅ |
✅ |
✅ |
✅ |
OpenAPI 支持 |
✅ |
✅ |
❌ |
❌ |
✅ |
模板引擎 |
✅ |
✅ |
❌ |
✅ |
✅ |
后台任务 |
✅ |
✅ |
❌ |
❌ |
✅ |
示例应用¶
litestar-pg-redis-docker :除了 Litestar 外,展示了应用模块化、SQLAlchemy 2.0 ORM、Redis 缓存等模式。像所有 Litestar 项目一样,该项目欢迎贡献。
litestar-fullstack :一个功能齐全、面向生产的全栈 Litestar Web 应用,采用最佳实践配置。它包含 SQLAlchemy 2.0、ReactJS、Vite、SAQ job queue、
Jinja模板等。 阅读更多。litestar-hello-world: 一个最小化应用示例,适合测试与 POC。