開始使用

安裝

pip install litestar

小訣竅

litestar[standard] includes commonly used extras like CLI, uvicorn and jinja2 (for templating).

Extras :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]'

Prometheus Instrumentation

pip install 'litestar[prometheus]'

Open Telemetry Instrumentation

pip install 'litestar[opentelemetry]'

SQLAlchemy (via Advanced-Alchemy)

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]'

備註

The full extras is not recommended because it will add a lot of unnecessary extras.

最小範例

At a minimum, make sure you have installed litestar[standard], which includes uvicorn.

First, create a file named app.py with the following contents:

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])

Then, run the following command:

litestar run
# Or you can run Uvicorn directly:
uvicorn app:app --reload

You can now visit http://localhost:8000/ and http://localhost:8000/books/1 in your browser and you should see the responses of your two endpoints:

"Hello, world!"

and

{"book_id": 1}

小訣竅

You can also check out the automatically generated OpenAPI-based documentation at:

  • 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)

You can check out a more in-depth tutorial in the Developing a basic TODO application section!

Expanded Example

Define your data model using pydantic or any library based on it (for example ormar, beanie, SQLModel):

from pydantic import BaseModel, UUID4


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

You can also use dataclasses (standard library and Pydantic), typing.TypedDict, or 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)

Define a Controller for your data model:

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

When instantiating your app, import your controller into your application's entry-point and pass it to Litestar:

from litestar import Litestar

from my_app.controllers.user import UserController

app = Litestar(route_handlers=[UserController])

To run your application, use an ASGI server such as uvicorn :

uvicorn my_app.main:app --reload

理念

  • Litestar 是一個由社群驅動的專案。這意味著該專案並非由單一作者領導,而是由一個核心維護團隊帶領,並得到貢獻者社群的支援。Litestar 目前擁有 5 位維護者,且正處於非常活躍的開發狀態。

  • Litestar draws inspiration from NestJS - a contemporary TypeScript framework - which places opinions and patterns at its core.

  • While still allowing for function-based endpoints, Litestar seeks to build on Python's powerful and versatile OOP, by placing class-based controllers at its core.

  • Litestar 並微框架。與 FastAPI、Starlette 或 Flask 等框架不同,Litestar 開箱即用,內建了許多現代 Web 應用程式所需的各項功能,例如 ORM 整合、客戶端與伺服器端會話、快取、OpenTelemetry 整合等。它的目標並非成為「下一個 Django」(例如,它永遠不會推出自己的 ORM),但其規模也絕非微型。

Feature comparison with similar frameworks

Litestar 與其他框架

功能

Litestar

FastAPI

Starlette

Sanic

Quart

OpenAPI

自動化 API 文件

Swagger, ReDoc, Stoplight Elements

Swagger, ReDoc

Data validation

Dependency Injection

Class based routing

Extension

ORM 整合

SQLAlchemy, Tortoise, Piccolo

Extension

Templating

Jinja, Mako

Jinja

Jinja

Jinja

Jinja

MessagePack

CORS

Extension

CSRF

Rate-limiting

Extension

JWT

Sessions

Client-side

Client-side

Client-side

Authentication

JWT / Session based

Caching

Example Applications

  • litestar-pg-redis-docker : In addition to Litestar, this demonstrates a pattern of application modularity, SQLAlchemy 2.0 ORM, Redis cache connectivity, and more. Like all Litestar projects, this application is open to contributions, big and small.

  • litestar-fullstack : A fully-capable, production-ready fullstack Litestar web application configured with best practices. It includes SQLAlchemy 2.0, ReactJS, Vite, SAQ job queue, Jinja templates and more. Read more.

  • litestar-hello-world: A bare-minimum application setup. Great for testing and POC work.