D
DSG54562/topic-89-model
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

足球平台开发当日赛程后端逻辑框架

问题背景

足球平台需要向前端稳定提供「当日赛程」数据,包括赛事编号、联赛名称、主队、客队、开赛时间、比赛状态等。当日赛程数据在业务上具有以下典型特征:

  • 数据来源多样:赛程可能来自上游数据供应商的接口推送、运营人员的人工录入或定时抓取,不同来源的字段命名与格式并不一致。
  • 更新频繁:开赛时间可能被官方修正,比赛状态(未开始、进行中、已结束)与比分会在比赛进行中持续变化。
  • 时间敏感:赛程按自然日划分,需要统一的时区换算规则,避免跨日数据错乱,也避免凌晨比赛被归到错误日期。
  • 读多写少:开赛前后同一批赛程会被大量用户同时查询,需要缓存层降低数据库压力,同时保证数据不过期失真。

如果直接把上游原始数据透传给前端,会出现字段不一致、重复比赛、状态过期、时区错乱等问题。因此需要一个当日赛程后端逻辑框架,负责数据的接入、清洗、归一化、存储、缓存与对外查询。

实现方案

总体架构

框架采用分层结构:

  1. 接入层(Ingestion):订阅上游赛程数据源,接收实时推送或定时拉取,统一入口进入管道。
  2. 归一化层(Normalization):将不同来源的数据转换为统一的内部赛程模型,补全缺失字段、统一状态枚举。
  3. 存储层(Storage):保存当日赛程明细以及每条记录的内容指纹,用于精确判定数据是否发生变化。
  4. 缓存层(Cache):为高频查询提供短期缓存,降低数据库读取压力。
  5. 查询层(API):对外提供当日赛程列表、单场详情等查询接口。

当日赛程划分

以服务端配置的时区(示例使用 Asia/Shanghai)计算「当日」时间区间 [当日 00:00, 次日 00:00),再按开赛时间过滤赛程。所有内部时间统一以 UTC 存储,仅在划分当日与展示时转换为目标时区,避免跨日数据被错误聚合。

去重与精确更新

使用布隆过滤器做快速存在性判断以减少存储查询;布隆过滤器命中后必须通过精确记录(内容指纹)确认,不得直接跳过新内容,也不得直接跳过已有内容的更新:

  • 指纹不存在 → 属于新内容,写入赛程内容并写入指纹。
  • 指纹存在且相同 → 内容未变化,跳过。
  • 指纹存在但不同 → 内容已更新,同时更新赛程内容与指纹。

数据一致性

每次更新携带自增版本号,写入时只接受版本不低于当前值的记录,避免旧数据覆盖新数据。

代码示例

以下示例为 Python 3.10+ 的演示实现,依赖 redis-py 与标准库 sqlite3、hashlib、zoneinfo。执行方式:在项目目录安装依赖后运行 python main.py。

依赖

  • Python 3.10+
  • redis-py(Redis 客户端,用于布隆过滤器与查询缓存)
  • 标准库:sqlite3、hashlib、json、dataclasses、zoneinfo

示例一:赛程归一化与当日划分

import hashlib
import json
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo


@dataclass
class Match:
    """内部统一的赛程模型,时间统一为 UTC。"""
    match_id: str
    league: str
    home_team: str
    away_team: str
    kickoff_at: datetime          # UTC 时间
    status: str = "not_started"   # not_started / live / finished
    version: int = 1


def normalize(raw: dict) -> Match | None:
    """把上游原始数据归一化为内部赛程模型。"""
    try:
        kickoff_utc = datetime.fromisoformat(raw["kickoff"]).astimezone(timezone.utc)
    except (KeyError, ValueError, TypeError):
        return None
    return Match(
        match_id=str(raw["match_id"]),
        league=raw.get("league", "unknown"),
        home_team=raw.get("home", ""),
        away_team=raw.get("away", ""),
        kickoff_at=kickoff_utc,
    )


def is_today(match: Match, day: datetime, tz: ZoneInfo) -> bool:
    """按目标时区判断赛程是否属于 day 对应的自然日。"""
    local = match.kickoff_at.astimezone(tz)
    start = day.astimezone(tz).replace(hour=0, minute=0, second=0, microsecond=0)
    end = start + timedelta(days=1)
    return start <= local < end


def fingerprint(match: Match) -> str:
    """对赛程内容计算 SHA-256 指纹,用于精确记录确认。"""
    payload = json.dumps({
        "match_id": match.match_id,
        "league": match.league,
        "home_team": match.home_team,
        "away_team": match.away_team,
        "kickoff_at": match.kickoff_at.isoformat(),
        "status": match.status,
    }, sort_keys=True, ensure_ascii=False)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()

预期结果:给定一条上游数据,normalize 输出统一的 Match 对象;is_today 按目标时区返回是否为当日赛程;fingerprint 对赛程内容生成稳定指纹,内容变化后指纹随之变化。

示例二:布隆过滤器与精确记录确认

import redis


class SqliteStore:
    """SQLite 存储层:保存赛程内容与内容指纹,支持批量事务。"""

    def __init__(self, db_path: str):
        import sqlite3
        self.conn = sqlite3.connect(db_path)
        self.conn.execute(
            "CREATE TABLE IF NOT EXISTS matches ("
            "match_id TEXT PRIMARY KEY, league TEXT, home TEXT, away TEXT, "
            "kickoff TEXT, status TEXT, version INTEGER)"
        )
        self.conn.execute(
            "CREATE TABLE IF NOT EXISTS fingerprints ("
            "match_id TEXT PRIMARY KEY, fp TEXT)"
        )
        self.conn.commit()

    def get_fingerprint(self, match_id: str) -> str | None:
        cur = self.conn.execute(
            "SELECT fp FROM fingerprints WHERE match_id = ?", (match_id,))
        row = cur.fetchone()
        return row[0] if row else None

    def upsert(self, match: Match) -> None:
        self.conn.execute(
            "INSERT INTO matches (match_id, league, home, away, kickoff, status, version) "
            "VALUES (?, ?, ?, ?, ?, ?, ?) "
            "ON CONFLICT(match_id) DO UPDATE SET "
            "league=excluded.league, home=excluded.home, away=excluded.away, "
            "kickoff=excluded.kickoff, status=excluded.status, "
            "version=excluded.version WHERE excluded.version >= matches.version",
            (match.match_id, match.league, match.home_team, match.away_team,
             match.kickoff_at.isoformat(), match.status, match.version),
        )

    def set_fingerprint(self, match_id: str, fp: str) -> None:
        self.conn.execute(
            "INSERT INTO fingerprints (match_id, fp) VALUES (?, ?) "
            "ON CONFLICT(match_id) DO UPDATE SET fp=excluded.fp",
            (match_id, fp),
        )

    def find_today(self, day: datetime, tz: ZoneInfo) -> list[Match]:
        start = day.astimezone(tz).replace(hour=0, minute=0, second=0, microsecond=0)
        end = start + timedelta(days=1)
        start_utc = start.astimezone(timezone.utc).isoformat()
        end_utc = end.astimezone(timezone.utc).isoformat()
        rows = self.conn.execute(
            "SELECT match_id, league, home, away, kickoff, status, version "
            "FROM matches WHERE kickoff >= ? AND kickoff < ?",
            (start_utc, end_utc),
        ).fetchall()
        return [
            Match(match_id=r[0], league=r[1], home_team=r[2], away_team=r[3],
                  kickoff_at=datetime.fromisoformat(r[4]), status=r[5], version=r[6])
            for r in rows
        ]

    def transaction(self):
        return self.conn


BF_KEY = "schedule:bloom"


class ScheduleUpdater:
    """把赛程写入存储层,布隆过滤器命中后必须用精确指纹确认。"""

    def __init__(self, store: SqliteStore, bloom: redis.Redis):
        self.store = store
        self.bloom = bloom

    def upsert_match(self, match: Match) -> str:
        fp = fingerprint(match)
        # 布隆过滤器只做快速判断,可能误判
        maybe_exists = self.bloom.bf().exists(BF_KEY, match.match_id)
        if maybe_exists:
            # 命中后必须用精确记录确认,不能直接跳过
            old = self.store.get_fingerprint(match.match_id)
            if old is not None and old == fp:
                return "unchanged"
        # 精确确认不存在或指纹变化,才同时更新内容与指纹
        self.store.upsert(match)
        self.store.set_fingerprint(match.match_id, fp)
        self.bloom.bf().add(BF_KEY, match.match_id)
        return "upserted"

预期结果:对同一场比赛重复写入时,第二次因精确指纹相同返回 unchanged;修改比赛状态后指纹变化,返回 upserted 并实际更新内容与指纹。

示例三:批量写入(实际批量提交)

def batch_upsert(updater: ScheduleUpdater, matches: list[Match]) -> dict[str, int]:
    """在单个事务内对整批赛程执行实际批量提交。"""
    result = {"unchanged": 0, "upserted": 0}
    conn = updater.store.transaction()
    try:
        for m in matches:
            action = updater.upsert_match(m)
            result[action] += 1
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    return result

预期结果:一次调用把整批赛程在同一事务内提交到存储层并回填布隆过滤器,返回 unchanged / upserted 计数;任一条失败则整批回滚。

示例四:当日赛程查询 API

class ScheduleReader:
    """对外查询:先查缓存,未命中再查存储层并回填缓存。"""

    def __init__(self, store: SqliteStore, cache: redis.Redis, ttl: int = 60):
        self.store = store
        self.cache = cache
        self.ttl = ttl

    def query_daily(self, day: datetime, tz: ZoneInfo) -> list[dict]:
        cache_key = f"daily:{day.date().isoformat()}"
        cached = self.cache.get(cache_key)
        if cached is not None:
            return json.loads(cached)
        rows = self.store.find_today(day, tz)
        payload = [
            {
                "match_id": m.match_id,
                "league": m.league,
                "home": m.home_team,
                "away": m.away_team,
                "kickoff": m.kickoff_at.isoformat(),
                "status": m.status,
            }
            for m in rows
        ]
        self.cache.set(cache_key, json.dumps(payload, ensure_ascii=False), ex=self.ttl)
        return payload

预期结果:首次查询读取存储层并回填缓存,TTL 内再次查询直接返回缓存结果,数据与存储层一致。

执行方式与预期结果

将上述示例整合到 main.py,包含入口函数:

def main() -> None:
    tz = ZoneInfo("Asia/Shanghai")
    today = datetime.now(tz)
    store = SqliteStore("schedule.db")
    bloom = redis.Redis(host="127.0.0.1", port=6379, db=0)
    updater = ScheduleUpdater(store, bloom)
    reader = ScheduleReader(store, bloom)
    # 示例输入:两条上游原始记录
    raws = [
        {"match_id": 1, "league": "英超", "home": "A队", "away": "B队",
         "kickoff": "2026-10-01T19:30:00+08:00"},
        {"match_id": 2, "league": "西甲", "home": "C队", "away": "D队",
         "kickoff": "2026-10-02T02:00:00+08:00"},
    ]
    matches = [m for m in (normalize(r) for r in raws) if m is not None and is_today(m, today, tz)]
    print(batch_upsert(updater, matches))
    print(reader.query_daily(today, tz))


if __name__ == "__main__":
    main()

运行 python main.py 后,控制台输出批量更新计数与当日赛程 JSON 列表。以上示例依赖本地 Redis(127.0.0.1:6379)与 SQLite 存储,尚未在实际仓库环境运行,标注为待验证。

验证方法

  1. 归一化验证:用样例上游原始记录构造输入,断言 normalize 输出字段完整、时间为 UTC。
  2. 时区验证:分别以 Asia/Shanghai 与 UTC 验证 is_today,确认当日边界正确、凌晨比赛归入正确日期。
  3. 去重验证:对同一场比赛重复写入,断言第二次返回 unchanged,内容未被覆盖,也未跳过新内容。
  4. 更新验证:修改比赛状态后重新写入,断言指纹变化并实际更新内容与指纹。
  5. 批量验证:构造含合法与非法记录的数据集,断言合法记录在同一事务内批量提交、非法输入被回滚。
  6. 缓存验证:连续查询同一日期,断言命中缓存且返回结果与存储层一致。
  7. 端到端验证:运行 python main.py,检查输出的更新计数与当日赛程列表字段完整性。

说明:以上验证步骤为本次设计中的计划项,尚未在真实环境产生通过记录;本文档不宣称任何测试已通过,也不提供任何实测性能数据。

局限性

  • 本文档只描述当日赛程后端逻辑框架的设计与示例,不包含前端展示、推送通知、赔率模块等周边功能。
  • 上游数据字段与质量的假设来自一般性行业经验,未针对任何具体供应商做适配。
  • 布隆过滤器存在误判可能,精确确认需要额外的指纹存储与查询开销。
  • 缓存 TTL 为固定值,未覆盖赛程临近开赛时的主动失效策略。
  • 示例依赖本地 Redis 与 SQLite,未经生产环境压测,缺少性能数据。
  • 未覆盖多数据中心部署、消息队列削峰、故障转移等大规模场景。

用户提供的网址(未核验)

以下网址由任务提供,仅作记录使用。本框架未访问、未抓取、未读取、未解析、未核验其内容、可访问性与相关性,不作为本文档任何技术结论的证明。

GitHub 链接(3 条)

  1. https://github.com/zaniyahcooko/yqbams/blob/main/2026%E5%B9%B410%E6%9C%88%E6%A0%B8%E5%BF%83%E5%9B%A2%E9%98%9F%E9%A2%84%E6%B5%8B-%E7%AB%9E%E5%BD%A9%E8%B6%B3%E7%90%83%E6%8E%A8%E8%8D%90-%E5%AE%9D%E5%86%A0%E8%B4%A2%E7%BB%8F.md
  2. https://github.com/zaniyahcooko/guhlhg/blob/main/2026%E5%B9%B410%E6%9C%88%E8%B5%9B%E6%9E%9C%E7%B2%BE%E5%87%86%E9%A2%84%E6%B5%8B-%E4%BB%8A%E6%97%A5%E7%B2%BE%E9%80%89%E8%B6%B3%E7%90%83%E6%8E%A8%E8%8D%90-%E6%99%BA%E9%A2%86%E8%B4%A2%E7%BB%8F.md
  3. https://github.com/zaniyahcooko/yqbams/blob/main/2026%E5%B9%B410%E6%9C%88%E7%B2%BE%E5%87%86%E7%B2%BE%E9%80%89%E9%A2%84%E6%B5%8B-%E6%AC%A7%E8%81%94%E6%9D%AF%E8%B6%B3%E7%90%83%E9%A2%84%E6%B5%8B-%E7%91%9E%E4%B8%B0%E8%B4%A2%E7%BB%8F.md

外部链接(3 条)

  1. https://bshsms.northrex.cn/article/jin-ri-zu-6
  2. https://bshsms.northrex.cn/article/jin-ri-zu-4
  3. https://bshsms.northrex.cn/article/jin-ri-zu-3