MCPcopy Create free account
hub / github.com/ZyphrZero/z.ai2api_python / sync_token_stats_to_db

Function sync_token_stats_to_db

app/utils/token_pool.py:638–685  ·  view source on GitHub ↗

将内存中的 Token 统计同步到数据库 应在服务关闭或定期调用,确保统计数据不丢失

()

Source from the content-addressed store, hash-verified

636
637
638async def sync_token_stats_to_db():
639 """
640 将内存中的 Token 统计同步到数据库
641
642 应在服务关闭或定期调用,确保统计数据不丢失
643 """
644 pool = get_token_pool()
645 if not pool:
646 return
647
648 from app.services.token_dao import get_token_dao
649
650 dao = get_token_dao()
651
652 pending_updates = []
653 with pool._lock:
654 for token, status in pool.token_statuses.items():
655 pending_success = max(
656 0,
657 status.successful_requests - status.db_synced_successful_requests,
658 )
659 pending_failure = max(
660 0,
661 status.failed_requests - status.db_synced_failed_requests,
662 )
663 if pending_success > 0 or pending_failure > 0:
664 pending_updates.append(
665 (
666 token,
667 status.token_id,
668 pending_success,
669 pending_failure,
670 )
671 )
672
673 for token, token_id, pending_success, pending_failure in pending_updates:
674 for _ in range(pending_success):
675 await dao.record_success(token_id)
676 for _ in range(pending_failure):
677 await dao.record_failure(token_id)
678
679 with pool._lock:
680 if token in pool.token_statuses:
681 status = pool.token_statuses[token]
682 status.db_synced_successful_requests += pending_success
683 status.db_synced_failed_requests += pending_failure
684
685 logger.info("✅ Token 统计已同步到数据库")

Calls 4

get_token_daoFunction · 0.90
get_token_poolFunction · 0.85
record_successMethod · 0.80
record_failureMethod · 0.80