使用场景与最佳实践
本文详细说明 CNB 当后端的 5 个典型实战场景,每个场景包含数据结构设计、读写流程和完整代码示例。
场景一:微型 CMS(博客/文章管理)
思路
文章用 Markdown 文件存储,每个文章一个目录,包含元信息和正文。API 直接读取渲染,Git Push 发布新文章。
目录结构
data/
├── posts/
│ ├── 2026-05-29-enterprise-loan/
│ │ ├── meta.json # 文章元信息
│ │ └── content.md # 正文
│ ├── 2026-05-20-ai-agent/
│ │ ├── meta.json
│ │ └── content.md
│ └── index.json # 文章索引(自动生成)meta.json 示例
json
{
"title": "企业贷款利率跌至3.1%创历史新低",
"author": "鸿爪派",
"tags": ["融资", "贷款", "中小企业"],
"published_at": "2026-05-29T10:00:00Z",
"status": "published",
"cover_image": "images/cover.jpg"
}读取流程
python
# 1. 获取文章列表
entries = db.list_files("data/posts")
# 2. 读取每篇文章的 meta.json
for entry in entries:
if entry["type"] == "tree":
meta = db.read_json(f"data/posts/{entry['name']}/meta.json")
if meta.get("status") == "published":
print(meta["title"])
# 3. 读取文章正文
content = db.read_file("data/posts/2026-05-29-enterprise-loan/content.md")发布流程
bash
# 新建文章目录
mkdir data/posts/2026-06-01-new-article
# 写入元信息和正文
echo '{"title":"新文章","status":"draft"}' > data/posts/2026-06-01-new-article/meta.json
echo "# 新文章标题\n\n正文内容..." > data/posts/2026-06-01-new-article/content.md
# Push 发布
git add . && git commit -m "feat: 新增文章" && git push场景二:多环境配置中心
思路
用目录层级区分环境,JSON/YAML 文件存储配置。Git 提交历史 = 配置变更审计日志,分支 = 配置隔离环境。
目录结构
config/
├── production/
│ ├── database.json
│ ├── features.json
│ └── third-party.json
├── staging/
│ ├── database.json
│ ├── features.json
│ └── third-party.json
├── development/
│ └── database.json
└── shared/
└── common.json读取流程
python
# 根据环境变量决定读取哪个配置
import os
env = os.getenv("APP_ENV", "development")
db_config = db.read_json(f"config/{env}/database.json")
print(f"DB Host: {db_config['host']}")
print(f"DB Port: {db_config['port']}")优势
- 版本追溯:
git log config/production/查看所有生产环境配置变更 - 回滚:
git checkout {old_sha} -- config/production/秒级回滚 - 差异对比:
GET /-/git/compare/{old_sha}..{new_sha}API 级别对比 - 分支隔离:staging 分支测试配置 → 合并到 main 生效
场景三:数据采集与存储
思路
定时任务(NPC / Cron)采集外部数据,格式化为 JSON 后 Git Push 到仓库。仓库就是数据湖,CNB API 就是查询接口。
目录结构
data/
├── weather/
│ ├── 2026-05-29.json # 每日一条记录
│ └── 2026-05-28.json
├── news/
│ ├── 2026-05-29/
│ │ ├── tech.json
│ │ └── finance.json
│ └── 2026-05-28/
│ └── tech.json
└── metrics/
└── daily-2026-05.json # 按月汇总采集 + 写入脚本
python
import json, subprocess
from datetime import date
def collect_and_save(data: dict, category: str):
"""采集数据并保存到仓库"""
today = date.today().isoformat()
filepath = f"data/{category}/{today}.json"
# 写入文件
with open(filepath, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# Git commit + push
subprocess.run(["git", "add", filepath])
subprocess.run(["git", "commit", "-m", f"data: {category} {today}"])
subprocess.run(["git", "push", "origin", "main"])
# 使用
collect_and_save({"temp": 28, "humidity": 65}, "weather")查询最近 7 天数据
python
from datetime import date, timedelta
for i in range(7):
day = (date.today() - timedelta(days=i)).isoformat()
try:
data = db.read_json(f"data/weather/{day}.json")
print(f"{day}: {data}")
except:
print(f"{day}: 无数据")场景四:Issue 驱动的工单系统
思路
CNB 的 Issue 系统天然支持标题、正文、标签、评论、指派。配合 Label 做分类,把 Issue 当作工单/订单/任务使用。
标签设计
标签分类:
- type: order / task / bug / feature
- status: todo / doing / done
- priority: high / medium / low创建工单
python
# 创建一个新订单
db.create_issue(
title="客户A - 定制开发订单",
body="**客户**: 客户A公司\n**金额**: 50000元\n**交付日期**: 2026-06-15\n\n需求详情:...",
labels=["order", "todo", "high"]
)查询工单
python
# 查询所有未完成订单
issues = db.list_issues(state="open")
orders = [i for i in issues if "order" in str(i.get("labels", []))]
for order in orders:
print(f"#{order['number']} {order['title']} [{order.get('state','')}]")评论追踪进度
python
# 添加进度评论
resp = requests.post(
f"{db.base}/-/issues/{issue_number}/comments",
headers={**db.headers, "Content-Type": "application/json"},
json={"body": "**进度更新**: 已完成初步方案设计,等待客户确认。"}
)场景五:应用状态管理
思路
用一个 JSON 文件记录应用的运行状态、计数器、配置快照。每次变更 push 一条 commit,形成完整的状态变更历史。
state.json 示例
json
{
"version": "2.1.0",
"last_deploy": "2026-05-29T14:00:00Z",
"total_users": 1280,
"active_subscriptions": 456,
"maintenance_mode": false,
"feature_flags": {
"new_ui": true,
"ai_search": false,
"dark_mode": true
},
"announcements": [
{"id": 1, "text": "系统将于周六凌晨维护", "active": true}
]
}读写模式
python
# 读取当前状态
state = db.read_json("state.json")
print(f"当前版本: {state['version']}")
print(f"用户总数: {state['total_users']}")
# 更新状态(本地修改后 push)
state["total_users"] += 1
with open("state.json", "w") as f:
json.dump(state, f, indent=2)
subprocess.run(["git", "add", "state.json"])
subprocess.run(["git", "commit", "-m", "state: 用户数 +1"])
subprocess.run(["git", "push"])状态历史回溯
python
# 通过 commit 历史查看状态变更
commits = requests.get(
f"{db.base}/-/git/commits",
headers=db.headers,
params={"path": "state.json"}
).json()
for c in commits[:10]:
print(f"{c['sha'][:8]} | {c['message']}")最佳实践总结
目录组织原则
your-repo/
├── data/ # 业务数据(JSON/CSV/YAML)
│ ├── users/
│ ├── orders/
│ └── config/
├── docs/ # 文档(Markdown)
├── scripts/ # 自动化脚本
├── assets/ # 静态资源(图片/PDF)
└── state.json # 应用状态文件命名规范
- 数据文件:使用小写 + 短横线,如
user-profiles.json - 日期目录:ISO 格式,如
2026-05-29 - Commit message:遵循 Conventional Commits,如
feat: add user record - Label:用前缀分类,如
type:order、status:done
安全提醒
- 私有仓库:存储敏感数据时必须使用私有仓库
- Token 管理:定期轮换 Token,不要在代码中硬编码
- 文件大小:单个文件建议不超过 1MB
- Push 频率:避免过于频繁的 Push(建议间隔 > 30 秒)
- 备份策略:定期 clone 到本地作为备份