deffetch_latest_release(source=None):
source = source or pick_channel()
primary, fallback = (source, 'gitcode'if source == 'github'else'github')
for s in (primary, fallback): # 首选失败自动切备选try:
info = _PROVIDERS[s].fetch()
if info andnot (info.prerelease and Setting.get('update_check_include_prerelease') != '1'):
return info
except Exception as e:
logger.warning('更新源 %s 获取失败:%s', s, e)
returnNone
ZhyCMS 后台自动更新检查与通知 实现方案(v3.1.11)
一、需求与设计边界
1.1 需求
1.2 关键边界(务必先对齐)
up即丢失;源码覆盖有签名缺失、依赖/迁移错配风险docker compose pull && up -d或git checkout tag)CMS_VERSION变化→横幅自动消失二、总体架构
降级原则:任何环节失败都静默降级(仅记
warning日志),绝不阻塞登录、不弹错误、不影响主流程。三、数据结构设计(复用 Setting,不新建表)
在
app/models/setting.py的Setting.DEFAULTS(:38-178)新增:update_check_enable'1'1/0)update_check_channel'auto'auto/github/gitcodeupdate_check_interval_hours'12'update_check_include_prerelease'0'update_check_ip_region''cn/overseasupdate_check_ip_region_at''update_check_last_at''update_check_result''ReleaseInfo+ has_update)update_check_dismissed''update_check_github_token''_secret? 不匹配后缀,需加入SENSITIVE_KEYS_EXPLICIT或改为update_check_github_secret)建议:GitHub Token 键命名为
update_check_github_secret,自动命中_secret后缀加密,无需改敏感键逻辑。update_check_result的 JSON 结构:{ "has_update": true, "current": "3.1.10", "latest": "3.1.11", "tag": "v3.1.11", "name": "v3.1.11 ...", "notes": "<原始 markdown 文本,展示前转义>", "published_at": "2026-11-11T10:00:00Z", "html_url": "https://github.com/pollybird/zhycms/releases/tag/v3.1.11", "download_url": "https://.../v3.1.11.zip", "source": "github", "prerelease": false, "checked_at": "2026-11-11T12:00:00+08:00" }四、出口 IP 地区检测(需求核心)
4.1 策略(分层,逐级降级)
4.2 关键实现约束
assert_safe_external_url(url, allowed_hosts={...}, allow_schemes=('https',));ip-api为http,单独放行其域名。allow_redirects=False:防止 30x 跳转到内网。update_check_channel设为具体站点时仍会探测连通性。4.3 重要设计修正:IP 地区只作"首选",不锁死
即使用 IP 判为海外,也先试首选、失败自动切备选(见第 5.3)。原因:IP 库可能误判、GitHub 在国内可能间歇可用、GitCode 也可能临时故障。这样"地区选择"是优化项而非单点故障。
4.4 代码骨架(
app/utils/update_check.py)_REGION_PROBES = [ ('https://myip.ipip.net', 'text'), ('https://ip.useragentinfo.com/json', 'json'), ('https://ipinfo.io/json', 'json'), ('https://ip-api.com/json/?lang=zh-CN', 'json'), ] def get_exit_ip_region(force=False): """返回 'cn' | 'overseas' | ''(未知)。带 7 天缓存。""" if not force: region = Setting.get('update_check_ip_region') at = Setting.get('update_check_ip_region_at') if region and _within_days(at, 7): return region region = _probe_region() or _probe_connectivity() or 'cn' Setting.set('update_check_ip_region', region) Setting.set('update_check_ip_region_at', _now_iso()) db.session.commit() return region def pick_channel(): """返回首选源 'github'|'gitcode'。""" cfg = Setting.get('update_check_channel', 'auto') if cfg in ('github', 'gitcode'): return cfg return 'gitcode' if get_exit_ip_region() == 'cn' else 'github'五、Release Provider 适配(字段已实测)
5.1 端点
https://api.github.com/repos/pollybird/zhycms/releases/latestAccept: application/vnd.github+json、User-Agent: ZhyCMS-UpdateCheck、可选Authorization: Bearer <token>https://api.gitcode.com/api/v5/repos/pollybird/ZhyCMS/releases/latestAccept: application/json、User-Agent5.2 字段映射(实测确认)
versiontag_name去前缀vtag_name去前缀vnamenamenamenotesbodybodypublished_atpublished_at(UTC)created_at(无 published_at)html_urlhtml_urlhttps://gitcode.com/pollybird/ZhyCMS/releases/tag/{tag}download_urlzipball_url或assets[0].browser_download_urlassets[0].browser_download_url(实测raw.gitcode.com/.../v3.1.7.zip)prereleaseprereleaseprerelease5.3 抓取与降级
def fetch_latest_release(source=None): source = source or pick_channel() primary, fallback = (source, 'gitcode' if source == 'github' else 'github') for s in (primary, fallback): # 首选失败自动切备选 try: info = _PROVIDERS[s].fetch() if info and not (info.prerelease and Setting.get('update_check_include_prerelease') != '1'): return info except Exception as e: logger.warning('更新源 %s 获取失败:%s', s, e) return Noneallow_redirects=False。assert_safe_external_url(url, allowed_hosts={'api.github.com','api.gitcode.com'}, allow_schemes=('https',))。app/plugin_system.py:version_cmp(已支持缺位补 0)。ReleaseInfo用dataclasses.dataclass。5.4 代码骨架
@dataclass class ReleaseInfo: version: str; tag: str; name: str; notes: str published_at: str; html_url: str; download_url: str prerelease: bool; source: str class _GitHubProvider: URL = 'https://api.github.com/repos/pollybird/zhycms/releases/latest' def fetch(self) -> ReleaseInfo: ... class _GitCodeProvider: URL = 'https://api.gitcode.com/api/v5/repos/pollybird/ZhyCMS/releases/latest' def fetch(self) -> ReleaseInfo: ...六、触发、频率与并发
6.1 触发点
admin/auth.py成功分支,login_user之后)update_check.maybe_trigger_async()admin/dashboard.py)check_for_update(force=True)同步返回结果6.2 频率门限
maybe_trigger_async():若now - update_check_last_at < interval直接返回;否则起 daemon 线程执行并写回last_at。6.3 多 worker 竞态
gunicorn 4 worker 下可能并发触发 → 最多重复 1–2 次外部请求(可接受)。可选优化:有 Redis 时用
SET NX EX站点锁;无 Redis 依赖 Setting 门限,容忍少量重复。七、UI 与交互
7.1 dashboard 横幅
仿现有"异地登录" warning 横幅(
dashboard.py:47-52的session.pop('login_abnormal_alert')模式):update_check_result,若has_update且tag != update_check_dismissed→ 渲染横幅:×→ POST/settings/update/dismiss(CSRF)→ 写update_check_dismissed=tag。7.2 更新内容弹窗
v3.1.10 → v3.1.11html_url)7.3 配置页
/settings/update(system:settings权限)X-CSRF-Token,限流10/minute)base.html"系统设置"子菜单新增"版本更新"(current_user.has_permission('system:settings'))八、更新内容的安全渲染(关键)
Release notes 是外部不可信内容,严禁直接
|safe。默认方案(零新依赖,推荐):
from markupsafe import escape def render_notes(notes: str) -> Markup: # 1) 转义全部 HTML;2) 保留换行;3) 不解析链接(防钓鱼) safe_text = str(escape(notes or '')) return Markup(safe_text.replace('\n', '<br>'))**bold**、`code`做最小化转换后再Markup,但需严格白名单;或引入bleach白名单清洗(需新增依赖,本次不采用)。九、更新指引与"重启提示"
9.1 Docker 部署(README 主推)
# 1) 备份(后台「备份运维」或命令行) # 2) 拉取并切换到新镜像 tag(或 latest) docker compose pull docker compose up -d # 3) 新容器启动时 entrypoint 自动执行 Alembic 迁移(如有)up -d重启;若使用外部反向代理/独立 gunicorn,请重启对应进程使新版本生效。"9.2 源码部署
git fetch --tags git checkout v3.1.11 pip install -r requirements.txt # 如有新依赖 flask db upgrade # 如有数据库迁移(看 Release notes 的“升级注意”) # 重启 gunicorn / systemd 服务9.3 "是否已生效"判定
Setting.CMS_VERSION变为新版本 → 横幅自动消失(has_update=false)。十、安全考量清单
allow_redirects=False+ 超时 3–6s|safesystem:settings;dismiss 需登录_csrf_token/X-CSRF-Token@limiter.limit('10/minute')_secret后缀键,自动 Fernet 加密audit_log十一、发布流程配套(重要前置)
实测发现:GitHub 与 GitCode 的 latest Release 均停留在 v3.1.7,而代码已到 v3.1.10。若不补齐 Release,更新检查将永远显示"无更新"(
version_cmp(latest=v3.1.7, current=v3.1.10) <= 0)。配套要求:
vX.Y.Z并创建 Release(notes 与 CHANGELOG 对应版本一致)。RELEASE.md发布清单或 CI 发布流程。十二、文件改动清单
app/utils/update_check.pyapp/admin/system/update.py/settings/update、/settings/update/check、/settings/update/dismissapp/admin/templates/admin/setting/update.htmlapp/admin/templates/admin/_update_modal.html(或并入 dashboard)app/models/setting.pyapp/admin/auth.pymaybe_trigger_async()app/admin/dashboard.pyapp/admin/templates/admin/dashboard.htmlapp/admin/templates/admin/base.htmlapp/utils/helpers.pyapp/admin/system/__init__.pyfrom . import update # noqa: F401(沿用现有域子包注册方式,路由仍挂admin_bp)tests/test_update_check.pyCHANGELOG.md/SECURITY.md/README.md/UPGRADE.md十三、测试计划
v3.1.10 < v3.1.11、相等、预发布过滤force=True必查<script>→ 输出被转义;SSRF 白名单拒绝非目标域名system:settings访问 403;dismiss 需登录 + CSRF十四、分阶段落地
update_check.py(地区检测/Provider/缓存)+ 登录触发 + dashboard 横幅 + 弹窗 + 重启提示附录 A:为何不做应用内自动更新(决策记录)
docker cp/容器内改代码会在重建时丢失;正确做法是替换镜像并由编排重启。附录 B(可选):源码部署"一键更新"约束(若将来要做)
is_super+ 二次确认(YES_I_UNDERSTAND)backup_utils.create_backup)方案完毕。 建议先确认两个前置项:① 需同步补齐 GitHub/GitCode 的 Release(否则检测不到);② 是否需要把"应用内一键更新"纳入范围(默认不做)。