You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
1.2 KiB
Python
54 lines
1.2 KiB
Python
from __future__ import annotations
|
|
|
|
import math
|
|
from typing import Any, Generic, TypeVar
|
|
|
|
from pydantic import BaseModel, ConfigDict
|
|
|
|
from iti.schemas import to_camel
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
class Envelope(BaseModel, Generic[T]):
|
|
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
|
|
|
|
data: T | None = None
|
|
code: int = 200
|
|
message: str = "成功"
|
|
|
|
|
|
def ok(data: Any = None, message: str = "成功", code: int = 200) -> dict[str, Any]:
|
|
return {"data": data, "code": code, "message": message}
|
|
|
|
|
|
def fail(
|
|
message: str = "操作失败", code: int = 500, data: Any = None
|
|
) -> dict[str, Any]:
|
|
return {"data": data, "code": code, "message": message}
|
|
|
|
|
|
def pagination(
|
|
*,
|
|
page: int = 1,
|
|
size: int = 10,
|
|
total: int = 0,
|
|
pages: int | None = None,
|
|
) -> dict[str, Any]:
|
|
pages = pages if pages is not None else math.ceil(total / size) if size > 0 else 0
|
|
return {
|
|
"page": page,
|
|
"size": size,
|
|
"pages": pages,
|
|
"total": total,
|
|
}
|
|
|
|
|
|
def page(
|
|
items: list[Any],
|
|
page_info: dict[str, Any] | None = None,
|
|
message: str = "成功",
|
|
code: int = 200,
|
|
) -> dict[str, Any]:
|
|
return ok({"items": items, "page": page_info or pagination()}, message, code)
|