Skip to main content

bootstrap-python

用 Pydantic 模型描述 Bootstrap 5 界面,并直接渲染成 HTML。

每个组件都是类型安全的 pydantic 模型:字段写错会立刻抛 ValidationError,文本默认转义, 组合与复用靠 Python 的列表和嵌套完成。交互(弹窗、抽屉、标签页、折叠面板、提示气泡)全部由 Bootstrap 的 data-bs-* 属性驱动,不需要 Vue/React,也不需要前端构建, 适合服务端渲染、后台页面、报表和邮件页面。

from bootstrap_ui import Page, Card, Table, Badge

page = Page(title="用户", body=[
    Card(title="用户列表", body=[
        Table(columns=["ID", "姓名"], rows=[[1, "张三"], [2, "李四"]]),
    ]),
])
print(page.render())      # 完整 HTML 文档

打开 demo.html 可以看到一个把所有组件组合起来的后台概览页 (导航栏、统计卡片、标签页表格、列表组、折叠面板、模态框、抽屉、分页、Toast)。

demo

弹窗与抽屉同样由组件描述,点击按钮即可打开:

modal


为什么用组件而不是拼 HTML

手写 HTML / 模板字符串 本库的组件模型
转义 容易漏,XSS 靠自觉 文本默认转义,可信片段需显式 raw()
结构 拼接字符串,缩进和闭合靠人肉 列表嵌套,标签自动闭合
字段校验 写错属性名浏览器静默忽略 pydantic extra="forbid",构造时直接报错
复用 复制粘贴片段 函数/类/列表推导,组合自由
改样式 全局搜替换 改一处 class_name 或组件默认值

同时要明确它不是什么:这不是前端框架,没有响应式状态、没有数据绑定、不做前端请求。 分页、筛选、行内编辑这类交互需要后端配合刷新页面,或自己补少量 JS; 如果页面需要复杂的前端交互,请直接用 React/Vue 或配套的前端方案,不要硬套本库。


安装

pip install bootstrap-python        # 从 PyPI 安装
pip install -e .                   # 本地开发

要求 Python ≥ 3.9、pydantic ≥ 2.5、jinja2 ≥ 3.1。

发行名是 bootstrap-python,导入名是 bootstrap_ui:pip install bootstrap-python 之后用 from bootstrap_ui import Page。

30 秒上手

from bootstrap_ui import Page, Card, Row, Col, Table, Badge, Color

page = Page(
    title="运营看板",
    navbar=None,
    body=[
        Row(gutter=3, children=[
            Col(md=6, body=[
                Card(title="今日订单", body=["1,284"]),
            ]),
            Col(md=6, body=[
                Card(title="状态", body=[Badge(text="正常", color=Color.success, pill=True)]),
            ]),
        ]),
        Table(
            columns=["订单号", "客户", "金额"],
            rows=[["#A-1042", "张伟", "¥ 1,280.00"]],
            striped=True,
        ),
    ],
)

page.save("dashboard.html")

生成结果:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  ...
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container py-4">
<div class="row g-3">
<div class="col-md-6"><div class="card h-100">...

三种输出

node.render()    # HTML 字符串(唯一真正用于交付的)
node.to_dict()   # 结构化描述:字段名、Bootstrap 类、子节点,可 JSON 序列化
node.to_json()   # 上面结果的 JSON 文本

to_dict() 保留子类的全部字段(借 pydantic 的 serialize_as_any),并自动去掉空的 attrs/style:

>>> Card(title="卡片", body=[Badge(text="x")]).to_dict()
{'body': [{'text': 'x', 'color': 'primary', 'pill': False}],
 'title': '卡片', 'actions': [], 'image_position': 'top'}

组件清单

分类 组件
页面/布局 Page Container Row Col Stack Box Fragment Hr
文本/内容 Heading Paragraph Span Strong Small Link Image Icon
卡片/列表 Card ListGroup ListItem Badge Alert
按钮 Button ButtonGroup CloseButton
导航 Navbar Nav NavItem Dropdown DropdownItem Breadcrumb Pagination
数据展示 Table TableColumn Progress Spinner Tabs TabItem Accordion AccordionItem Carousel
浮层 Modal Offcanvas Toast ToastContainer Tooltip
表单 Form FormGroup field() Label Input Textarea Select Checkbox RadioGroup InputGroup Fieldset Hidden
常量 Color Size Alignment Justify Placement Breakpoint
内核 Node RawHtml raw() render_attrs() render_children()

常用写法

# 表单:控件 + 标签 + 帮助文本
Form(action="/users", method="post", submit_label="保存", body=[
    field("姓名", Input(name="name", required=True), required=True),
    field("邮箱", Input(name="email", type="email"), help="用于接收通知"),
    field("角色", Select(name="role", placeholder="请选择",
                         options=[("管理员", "admin"), ("普通用户", "user")])),
    Checkbox(name="notify", label="保存后发送邮件", switch=True),
])

# 表格:字典行 + 组件单元格
Table(
    columns=[TableColumn(label="状态", key="status", align="center")],
    rows=[{"status": Badge(text="正常", color=Color.success)}],
)

# 弹窗:按钮和模态框用 id 关联
Button(text="新增", toggle_modal="user-modal")
Modal(id="user-modal", title="新增用户", body=[...], footer=[Button(text="取消", outline=True)])

# 抽屉
Button(text="筛选", toggle_offcanvas="filter-panel")
Offcanvas(id="filter-panel", title="筛选", placement="end", body=[...])

# 不产生包裹标签的组合,或插入可信 HTML
Span(body=[Icon(name="star-fill"), " 收藏"])
raw("<div class='ratio ratio-16x9'>…</div>")

字段约定

  • class_name → HTML 的 class(序列化为 "class"),用于追加任意 Bootstrap 工具类;
  • style 支持字符串或字典({"min-width": "10rem"},键里的 _ 会转成 -);
  • attrs 放任意原生属性,例如 attrs={"data-bs-toggle": "tooltip", "aria-label": "提示"};
  • 文本默认转义;只有 RawHtml / raw() 会原样输出;
  • 组件是 pydantic 模型(extra="forbid"),写错字段名会直接报 ValidationError,不会静默失效。

项目结构

bootstrap_ui/
  types.py       # Node 基类:属性渲染、转义、to_dict/to_json
  constants.py   # Color / Size / Alignment ...
  layout.py      # Page / Container / Row / Col / Stack / Box / Fragment / Hr
  content.py     # Heading / Span / Card / Alert / ListGroup / Button ...
  nav.py         # Navbar / Nav / Dropdown / Pagination / Breadcrumb
  data.py        # Table / Tabs / Accordion / Progress / Carousel / Spinner
  overlays.py    # Modal / Offcanvas / Toast / Tooltip
  forms.py       # Form / FormGroup / Input / Select / Checkbox / RadioGroup ...
  templates/
    page.jinja2  # HTML 外壳(CDN、主题、自动初始化 Toast 与 Tooltip)
demo.py          # 演示脚本:生成 demo.html
tests/           # 24 个单元测试(含 HTML 标签闭合检查)

运行

python demo.py                                  # 生成 demo.html
python -m unittest discover -s tests -v         # 运行测试(24 项)

已知限制

  1. 交互能力有限:分页、筛选、行内编辑都是静态 HTML,需要后端配合或自己写少量 JS;
  2. 不校验类名:class_name 里写错 Bootstrap 类不会报错(Bootstrap 本身也不校验);
  3. 组件按需扩展:目前覆盖常用组件,Toast 自动弹出、Tooltip 初始化由模板里的脚本统一处理;
  4. CDN 依赖:默认从 jsdelivr 加载 Bootstrap,离线场景请把资源下载到本地并改 Page(cdn=...) / Page(css=...)。

License

MIT

Metadata

Release files for bootstrap-python 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bootstrap-python 0.1.0
File Size Uploaded Provenance Actions
bootstrap_python-0.1.0.tar.gz 30.5 kB Without provenance Details for bootstrap_python-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bootstrap-python 0.1.0
File Interpreter ABI Platform Actions
bootstrap_python-0.1.0-py3-none-any.whl Python 3 none any Details for bootstrap_python-0.1.0-py3-none-any.whl

Total release size: 63.2 kB

Release files / bootstrap_python-0.1.0.tar.gz

Download URL bootstrap_python-0.1.0.tar.gz
Size 30.5 kB
Tags Source
SHA-256 checksum
How to use checksums
15c6cce61c58fb1a609b45dbffe7762dfec6cbc2b3def2966b463e04e07d3a20
BLAKE2b-256 checksum
How to use checksums
daf60262eb6993d6cce4d7079e4c8b883d6dc4b9b8149d1d7e9514ea07ca8771
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.5

Release files / bootstrap_python-0.1.0-py3-none-any.whl

Download URL bootstrap_python-0.1.0-py3-none-any.whl
Size 32.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0349c548d5a3c3d6acb0c414f67dd4167abf7d9c6c489f74eba84d6293c5b00a
BLAKE2b-256 checksum
How to use checksums
f646d6d6b5bcab07da04c6999e59d6c87985e27704fd42f5d38c14fc8f84d80d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.5

Security for bootstrap-python 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page