perf: кеширование detect_endpoint в flask.g — минус 2 HTTP-запроса (v1.2.41)

Результат код-ревью #2:
  get_client() и get_stand() вызывали detect_endpoint() независимо
  → двойной HTTP-запрос к Nubes API на каждый рендер страницы.

  _cached_detect(token) кеширует результат в flask.g на время запроса.
This commit is contained in:
2026-08-04 07:26:26 +04:00
parent 06137d6082
commit cc7805a429
2 changed files with 21 additions and 9 deletions
+20 -8
View File
@@ -28,10 +28,26 @@ Cookie (устанавливаются main.py:action=set_mode):
import base64
import json
from flask import request, current_app
from flask import request, current_app, g
from api.http_client import HttpClient, detect_endpoint, stand_name, STANDS
def _cached_detect(token):
"""detect_endpoint с кешированием на время запроса (flask.g).
get_client() и get_stand() вызывают detect_endpoint() независимо —
это двойной HTTP-запрос к Nubes API. Кеш в g решает проблему."""
cache = g.get('_detected_endpoint')
if cache is None:
g._detected_endpoint = cache = {}
if token not in cache:
endpoint = current_app.config["NUBES_API_ENDPOINT"]
if endpoint in STANDS:
endpoint = detect_endpoint(token) or endpoint
cache[token] = endpoint
return cache[token]
def get_mode():
"""Режим: 'polygon' (эмуляция) или 'cloud' (реальное облако).
@@ -76,11 +92,8 @@ def get_client():
# Простая замена "/api/v1/svc" → "/{stand}/api/v1/svc"
return HttpClient(polygon.replace("/api/v1/svc", f"/{stand}/api/v1/svc"), token)
# Облако: NUBES_API_ENDPOINT с автоопределением
endpoint = current_app.config["NUBES_API_ENDPOINT"]
if endpoint in STANDS:
endpoint = detect_endpoint(token) or endpoint
return HttpClient(endpoint, token)
# Облако: NUBES_API_ENDPOINT с автоопределением (кешированным)
return HttpClient(_cached_detect(token), token)
def get_real_client():
@@ -131,8 +144,7 @@ def get_stand():
if endpoint not in STANDS:
s = stand_name(endpoint)
return s if s != "?" else "mock"
endpoint = detect_endpoint(token) or endpoint
return stand_name(endpoint)
return stand_name(_cached_detect(token))
def get_token_info():