Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

TOML

官方文档: https://docs.python.org/zh-cn/3.12/library/tomllib.html

📌 一、TOML 是什么?

TOML(Tom’s Obvious Minimal Language) 是一种结构清晰、非常适合作为配置文件的格式,类似 INI,但语法更严格,支持更多数据类型。

被广泛用于:

  • pyproject.toml
  • Poetry
  • Black
  • Ruff
  • FastAPI 配置
  • 开发环境变量

📌 二、Python 如何读写 TOML

Python 没有内置 TOML,需要安装库:

安装推荐库:tomli(读)或 tomllib(Python 3.11+ 内置)

  • Python 3.11+:推荐使用内置 tomllib
  • Python 3.10-:推荐使用非常轻量的 tomli

Python 3.11+:

import tomllib

with open("config.toml", "rb") as f:
    data = tomllib.load(f)

Python 3.10 或更低:

pip install tomli
import tomli

with open("config.toml", "rb") as f:
    data = tomli.load(f)

✏️ 写入 TOML:使用 tomli_w 或 tomlkit

推荐:

pip install tomli-w

示例:

import tomli_w

data = {
    "server": {"host": "127.0.0.1", "port": 8080},
    "debug": True,
}

with open("config.toml", "wb") as f:
    tomli_w.dump(data, f)

输出:

[server]
host = "127.0.0.1"
port = 8080

debug = true

📌 三、TOML 基本语法速查

1. 键值对

title = "config system"
port = 8080
enabled = true

2. 表(类似 dict)

[database]
host = "localhost"
port = 3306

3. 嵌套表

[server.api]
url = "/v1"
timeout = 10

等同于 Python:

{"server": {"api": {"url": "/v1", "timeout": 10}}}

4. 数组

ports = [8001, 8002, 8003]

5. 数组表(类似 list of dict)

[[plugins]]
name = "redis"
enabled = true

[[plugins]]
name = "mysql"
enabled = false

等于 Python:

{
  "plugins": [
    {"name": "redis", "enabled": True},
    {"name": "mysql", "enabled": False},
  ]
}

6. 日期时间(内置支持 RFC3339)

time = 2025-02-20T08:00:00Z

Python 读取 -> datetime 对象。

📌 四、Python 读取 TOML 文件示例

config.toml:

[server]
host = "127.0.0.1"
port = 8080

[auth]
token = "abcd1234"
expires = 30

Python 读取:

import tomllib

with open("config.toml", "rb") as f:
    cfg = tomllib.load(f)

print(cfg["server"]["host"])
print(cfg["auth"]["token"])

📌 五、在 FastAPI 项目中加载 TOML 配置

settings.toml

[database]
url = "postgresql://user:pass@localhost/db"

[api]
debug = true

settings.py

import tomllib
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
config_path = BASE_DIR / "settings.toml"

with open(config_path, "rb") as f:
    cfg = tomllib.load(f)

DB_URL = cfg["database"]["url"]
DEBUG = cfg["api"]["debug"]

📌 六、写一个统一的 utils.toml 模块

# utils/toml.py

import tomllib
import tomli_w
from pathlib import Path
from typing import Any


def load(path: str | Path) -> dict:
    path = Path(path)
    with open(path, "rb") as f:
        return tomllib.load(f)


def save(path: str | Path, data: dict) -> None:
    path = Path(path)
    with open(path, "wb") as f:
        tomli_w.dump(data, f)

使用:

from utils.toml import load, save

config = load("config.toml")
save("out.toml", config)

📌 七、pyproject.toml 常用结构

你的项目中肯定会用到。

典型 pyproject.toml:

[project]
name = "my_app"
version = "1.0.0"
requires-python = ">=3.12"

[tool.black]
line-length = 100

[tool.ruff]
select = ["E", "F"]
ignore = ["E501"]

[tool.poetry]
packages = [{ include = "app" }]

📌 八、TOML vs JSON 哪个更适合作为配置文件?

特性 TOML JSON
注释支持
更适合人读写
配置分节结构
适合日志/配置 一般
更严格(少 bug)
支持多行字符串 一般

所以:

  • 配置文件(settings、工具配置) -> 用 TOML
  • 数据传输(API) -> 用 JSON / orjson

📌 九、总结(你只需要记住这些)

  1. Python 3.11 内置 tomllib -> 只能读
  2. 写入用:tomli_w
  3. TOML 的结构就是:
    • [table]
    • [[array of table]]
  4. Python 读取后就是普通 dict
  5. 最适合作为项目配置文件