litestar快速入门

1,398 阅读3分钟

litestar快速入门

1. 前言

本人一直在对于python的web框架进行研究,想找一个介于django重量级与fastAPI轻量级web之间的框架,用作中小项目的开发在跟群友吹逼与知乎上文章:《FastAPI已死,Litestar当立》的因素下,想对litestar进行研究,发现国内并没有针对性系统的中文文章,想结合litestar的官方文档,推广一下litestar在国内的影响力

本系列文章主要是基于Litestar官方文档的研究与翻译,并添加自己的见解,适合没有接触过python web框架的人进行查询,有能力的人还是看看官方文档加快学习进度。

Litestar官网链接

官方文档链接

本文来源官方文档原文链接

2. 安装

pip install litestar
# 安装标准版
pip install litestar[standard]
# 安装全部插件
pip install litestar[full]

litestar[standard]包括常用的附加功能,如uvicornjinja2

新手建议使用standard或者full,这样就不需要再安装额外的库,仅限学习环境使用full会增加很多不必要的附加功能

2.1. 插件介绍

  • litestar[pydantic]:pydantic插件,常用数据验证库
  • litestar[attrs]:简化类定义的库,与pydantic类似
  • litestar[brotli]:压缩中间件
  • litestar[cryptography]:加密插件
  • litestar[jwt]:JWT插件
  • litestar[redis]:redis插件
  • litestar[picologging]:高性能日志库,相当于加强版的logging
  • litestar[structlog]:结构化日志库
  • litestar[prometheus]:prometheus的客户端
  • litestar[opentelemetry]:OpenTelemetry的客户端
  • litestar[sqlalchemy]:数据库orm插件
  • litestar[cli]自 2.1.1 版起已弃用,础litestar安装现已包含 CLI 依赖项
  • litestar[jinja]:模板引擎
  • litestar[mako]

3. 官方最小实例

确保您已经安装了litestar[standard],或安装过uvicorn

创建app.py

# 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

自动生成api文档地址:

  • http://localhost:8000/schema (for ReDoc),
  • http://localhost:8000/schema/swagger (for Swagger UI),
  • http://localhost:8000/schema/elements (for Stoplight Elements)
  • http://localhost:8000/schema/rapidoc (for RapiDoc)

4. 扩展内容

4.1. 定义数据

使用 pydantic 或任何基于它的库(例如 ormar、beanie、SQLModel)定义您的数据模型:

from pydantic import BaseModel, UUID4

class User(BaseModel):
    first_name: str
    last_name: str
    id: UUID4

您还可以使用数据类(标准库和 Pydantic)、 typing.TypedDictmsgspec.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)

4.2. 在litestar使用

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: ...

实例化您的应用程序时,将您的控制器导入应用程序的入口点并将其传递给Litestar

from litestar import Litestar
from my_app.controllers.user import UserController

app = Litestar(route_handlers=[UserController])

4.3. 运行

uvicorn my_app.main:app --reload