足球平台需要向前端稳定提供「当日赛程」数据,包括赛事编号、联赛名称、主队、客队、开赛时间、比赛状态等。当日赛程数据在业务上具有以下典型特征:
如果直接把上游原始数据透传给前端,会出现字段不一致、重复比赛、状态过期、时区错乱等问题。因此需要一个当日赛程后端逻辑框架,负责数据的接入、清洗、归一化、存储、缓存与对外查询。
框架采用分层结构:
以服务端配置的时区(示例使用 Asia/Shanghai)计算「当日」时间区间 [当日 00:00, 次日 00:00),再按开赛时间过滤赛程。所有内部时间统一以 UTC 存储,仅在划分当日与展示时转换为目标时区,避免跨日数据被错误聚合。
使用布隆过滤器做快速存在性判断以减少存储查询;布隆过滤器命中后必须通过精确记录(内容指纹)确认,不得直接跳过新内容,也不得直接跳过已有内容的更新:
每次更新携带自增版本号,写入时只接受版本不低于当前值的记录,避免旧数据覆盖新数据。
以下示例为 Python 3.10+ 的演示实现,依赖 redis-py 与标准库 sqlite3、hashlib、zoneinfo。执行方式:在项目目录安装依赖后运行 python main.py。
sqlite3、hashlib、json、dataclasses、zoneinfoimport 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 计数;任一条失败则整批回滚。
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 存储,尚未在实际仓库环境运行,标注为待验证。
normalize 输出字段完整、时间为 UTC。Asia/Shanghai 与 UTC 验证 is_today,确认当日边界正确、凌晨比赛归入正确日期。unchanged,内容未被覆盖,也未跳过新内容。python main.py,检查输出的更新计数与当日赛程列表字段完整性。说明:以上验证步骤为本次设计中的计划项,尚未在真实环境产生通过记录;本文档不宣称任何测试已通过,也不提供任何实测性能数据。
以下网址由任务提供,仅作记录使用。本框架未访问、未抓取、未读取、未解析、未核验其内容、可访问性与相关性,不作为本文档任何技术结论的证明。