22.10.205
This commit is contained in:
66
get_data.py
66
get_data.py
@@ -71,7 +71,7 @@ LOG_CONFIG = {
|
||||
},
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"level": "DEBUG",
|
||||
"level": "WARNING",
|
||||
"formatter": "simple",
|
||||
"stream": "ext://sys.stdout",
|
||||
},
|
||||
@@ -238,7 +238,7 @@ def rewrite_file(filename: str, data: dict, directory: str = "JSON") -> None:
|
||||
try:
|
||||
with open(filepath, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
logger.debug(f"Файл {filepath} перезаписан.")
|
||||
logger.info(f"Файл {filepath} перезаписан.")
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при записи файла {filepath}: {e}")
|
||||
|
||||
@@ -256,7 +256,7 @@ def get_json(url: str, timeout: int = 10, verify_ssl: bool = True) -> dict | Non
|
||||
dict | None: Распарсенный JSON или None при ошибке.
|
||||
"""
|
||||
try:
|
||||
logger.debug(f"Пытаюсь получить данные с {url}")
|
||||
logger.info(f"Пытаюсь получить данные с {url}")
|
||||
response = requests.get(url, timeout=timeout, verify=verify_ssl)
|
||||
response.raise_for_status() # выбросит исключение, если статус != 2xx
|
||||
return response.json()
|
||||
@@ -292,7 +292,7 @@ def Game_Online2(game_id: int) -> dict | None:
|
||||
# Получаем данные старого матча
|
||||
game = get_json(build_url("game"))
|
||||
if game:
|
||||
logger.debug("У нас получилось получить данные со старого матча")
|
||||
logger.info("У нас получилось получить данные со старого матча")
|
||||
else:
|
||||
logger.warning(
|
||||
f"Не удалось получить данные старого матча: game_id={game_id}"
|
||||
@@ -330,7 +330,7 @@ def Game_Online2(game_id: int) -> dict | None:
|
||||
game["result"]["scoreByPeriods"] = box_score["result"].get("scoreByPeriods", [])
|
||||
game["result"]["fullScore"] = box_score["result"].get("fullScore", {})
|
||||
|
||||
logger.debug("Склеил данные по онлайн матчу")
|
||||
logger.info("Склеил данные по онлайн матчу")
|
||||
return game
|
||||
|
||||
except Exception as e:
|
||||
@@ -385,7 +385,7 @@ def Game_Online(game_id: int) -> dict | None:
|
||||
|
||||
game = get_json(build_url("game"))
|
||||
if game:
|
||||
logger.debug("У нас получилось получить данные со старого матча")
|
||||
logger.info("У нас получилось получить данные со старого матча")
|
||||
# Только если матч не в онлайн-режиме — кладём в кэш как 'old'
|
||||
if not is_online:
|
||||
with _GAME_CACHE_LOCK:
|
||||
@@ -456,7 +456,7 @@ def Game_Online(game_id: int) -> dict | None:
|
||||
game["result"]["scoreByPeriods"] = box_score["result"].get("scoreByPeriods", [])
|
||||
game["result"]["fullScore"] = box_score["result"].get("fullScore", {})
|
||||
|
||||
logger.debug("Склеил данные по онлайн матчу")
|
||||
logger.info("Склеил данные по онлайн матчу")
|
||||
|
||||
# Обновляем кэш и снимаем режим 'old'
|
||||
with _GAME_CACHE_LOCK:
|
||||
@@ -1492,17 +1492,17 @@ def Player_Stat_Season(player_id: str, season: str) -> dict:
|
||||
player_stat_season = get_json(url)
|
||||
|
||||
if not player_stat_season:
|
||||
logger.debug(f"Пустой ответ от API для игрока {player_id} за сезон {season}")
|
||||
logger.error(f"Пустой ответ от API для игрока {player_id} за сезон {season}")
|
||||
return {player_id: default_player_stats_season()}
|
||||
|
||||
items = player_stat_season.get("items")
|
||||
if items:
|
||||
logger.debug(
|
||||
logger.info(
|
||||
f"Данные за сезон {season} для игрока {player_id} успешно получены."
|
||||
)
|
||||
return {player_id: items[-2:]} # последние две записи: Sum и Avg
|
||||
|
||||
logger.debug(
|
||||
logger.warning(
|
||||
f"Нет данных на игрока {player_id} за сезон {season}. Вероятно, еще не играл."
|
||||
)
|
||||
return {player_id: default_player_stats_season()}
|
||||
@@ -1513,7 +1513,7 @@ def Player_all_game_in_season2(player_id: str, season:str) -> dict:
|
||||
player_games = get_json(url)
|
||||
# games = {}
|
||||
if not player_games:
|
||||
logger.debug(f"Пустой ответ от API для игрока {player_id}")
|
||||
logger.error(f"Пустой ответ от API для игрока {player_id}")
|
||||
return {player_id: default_player_stats_season()}
|
||||
|
||||
for i in player_games.get("items"):
|
||||
@@ -1526,7 +1526,7 @@ def Player_all_game2(player_id: str) -> dict:
|
||||
player_seasons = get_json(url)
|
||||
|
||||
if not player_seasons:
|
||||
logger.debug(f"Пустой ответ от API для игрока {player_id}")
|
||||
logger.error(f"Пустой ответ от API для игрока {player_id}")
|
||||
return {player_id: default_player_stats_season()}
|
||||
|
||||
seasons = player_seasons.get("result").get("seasons")
|
||||
@@ -1549,7 +1549,7 @@ def Player_all_game_in_season(player_id: str, season: str) -> List[Dict[str, Any
|
||||
url = f"{URL}api/abc/players/stats?tag={LEAGUE}&season={season}&id={player_id}"
|
||||
player_games = get_json(url)
|
||||
if not player_games:
|
||||
logger.debug(f"Пустой ответ от API для игрока {player_id}, сезон {season}")
|
||||
logger.error(f"Пустой ответ от API для игрока {player_id}, сезон {season}")
|
||||
return [
|
||||
] # возвращаем пустой список, чтобы тип был стабилен
|
||||
|
||||
@@ -1595,7 +1595,7 @@ def Player_all_game(player_id: str) -> List[Dict[str, Any]]:
|
||||
{"id": 2010},
|
||||
]
|
||||
if not isinstance(seasons, list) or not seasons:
|
||||
logger.debug(f"Нет сезонов для игрока {player_id}")
|
||||
logger.error(f"Нет сезонов для игрока {player_id}")
|
||||
return []
|
||||
|
||||
all_games: List[Dict[str, Any]] = []
|
||||
@@ -1700,15 +1700,15 @@ def Player_Stat_Career(player_id: str) -> dict:
|
||||
player_stat_career = get_json(url)
|
||||
|
||||
if not player_stat_career:
|
||||
logger.debug(f"Пустой ответ от API для игрока {player_id}")
|
||||
logger.error(f"Пустой ответ от API для игрока {player_id}")
|
||||
return {player_id: default_player_stats()}
|
||||
|
||||
items = player_stat_career.get("items")
|
||||
if items:
|
||||
logger.debug(f"Данные за карьеру игрока {player_id} успешно получены.")
|
||||
logger.info(f"Данные за карьеру игрока {player_id} успешно получены.")
|
||||
return {player_id: items[-2:]} # последние два сезона (Sum и Avg)
|
||||
|
||||
logger.debug(f"Данные на игрока {player_id} не найдены. Вероятно, новичок.")
|
||||
logger.warning(f"Данные на игрока {player_id} не найдены. Вероятно, новичок.")
|
||||
return {player_id: default_player_stats()}
|
||||
|
||||
|
||||
@@ -1717,15 +1717,15 @@ def Coach_Stat(coach_id: str, season: str, team_id: str) -> dict | None:
|
||||
coach_stat = get_json(url)
|
||||
|
||||
if not coach_stat:
|
||||
logger.debug(f"Пустой ответ от API для тренера {coach_id}")
|
||||
logger.error(f"Пустой ответ от API для тренера {coach_id}")
|
||||
return None
|
||||
|
||||
items = coach_stat.get("items")
|
||||
if items:
|
||||
logger.debug(f"Данные за карьеру тренера {coach_id} успешно получены.")
|
||||
logger.info(f"Данные за карьеру тренера {coach_id} успешно получены.")
|
||||
return {coach_id: items}
|
||||
|
||||
logger.debug(f"Данные для тренера {coach_id} не найдены. Возможно, он новичок.")
|
||||
logger.warning(f"Данные для тренера {coach_id} не найдены. Возможно, он новичок.")
|
||||
return None
|
||||
|
||||
|
||||
@@ -1991,7 +1991,7 @@ def Team_Both_Stat(stop_event: threading.Event) -> None:
|
||||
)
|
||||
|
||||
if not team_1.get("total") or not team_2.get("total"):
|
||||
logger.debug("Нет total у команд — пропускаю перезапись team_stats.json")
|
||||
logger.warning("Нет total у команд — пропускаю перезапись team_stats.json")
|
||||
stop_event.wait(TIMEOUT_ONLINE)
|
||||
continue
|
||||
|
||||
@@ -2051,7 +2051,7 @@ def Team_Both_Stat(stop_event: threading.Event) -> None:
|
||||
)
|
||||
|
||||
rewrite_file("team_stats", result_json)
|
||||
logger.debug("Успешно записаны данные в team_stats.json")
|
||||
logger.info("Успешно записаны данные в team_stats.json")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
@@ -2127,7 +2127,7 @@ def Referee(stop_event: threading.Event) -> None:
|
||||
)
|
||||
|
||||
rewrite_file("referee", referees)
|
||||
logger.debug("Успешно записаны судьи в файл")
|
||||
logger.info("Успешно записаны судьи в файл")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в Referee потоке: {e}", exc_info=True)
|
||||
@@ -2168,7 +2168,7 @@ def Scores_Quarter(stop_event: threading.Event) -> None:
|
||||
if len(parts) == 2:
|
||||
score_by_quarter[i]["score1"] = parts[0]
|
||||
score_by_quarter[i]["score2"] = parts[1]
|
||||
logger.debug("Счёт по четвертям получен из fullScore.")
|
||||
logger.info("Счёт по четвертям получен из fullScore.")
|
||||
|
||||
# Если нет fullScore, пробуем scoreByPeriods
|
||||
elif "scoreByPeriods" in game_data.get("result", {}):
|
||||
@@ -2176,10 +2176,10 @@ def Scores_Quarter(stop_event: threading.Event) -> None:
|
||||
for i, score in enumerate(periods[: len(score_by_quarter)]):
|
||||
score_by_quarter[i]["score1"] = str(score.get("score1", ""))
|
||||
score_by_quarter[i]["score2"] = str(score.get("score2", ""))
|
||||
logger.debug("Счёт по четвертям получен из scoreByPeriods.")
|
||||
logger.info("Счёт по четвертям получен из scoreByPeriods.")
|
||||
|
||||
else:
|
||||
logger.debug("Нет данных по счёту, сохраняем пустые значения.")
|
||||
logger.warning("Нет данных по счёту, сохраняем пустые значения.")
|
||||
|
||||
rewrite_file("scores", score_by_quarter)
|
||||
|
||||
@@ -2235,7 +2235,7 @@ def Status_Online(data: dict, stop_event: threading.Event) -> None:
|
||||
with game_status_lock:
|
||||
game_status_data = result
|
||||
rewrite_file("live_status", [game_status_data])
|
||||
logger.debug("Успешно записан онлайн-статус в файл.")
|
||||
logger.info("Успешно записан онлайн-статус в файл.")
|
||||
else:
|
||||
logger.warning("status_online_func вернула None — пропуск записи.")
|
||||
except Exception as e:
|
||||
@@ -2257,7 +2257,7 @@ def Play_By_Play(data: dict, stop_event: threading.Event) -> None:
|
||||
game_data = game_online_data
|
||||
|
||||
if not game_data:
|
||||
logger.debug("game_online_data отсутствует")
|
||||
logger.error("game_online_data отсутствует")
|
||||
stop_event.wait(TIMEOUT_DATA_OFF)
|
||||
continue
|
||||
|
||||
@@ -2285,7 +2285,7 @@ def Play_By_Play(data: dict, stop_event: threading.Event) -> None:
|
||||
|
||||
plays = game_data.get("result", {}).get("plays", [])
|
||||
if not plays:
|
||||
logger.debug("нет данных в play-by-play")
|
||||
logger.warning("нет данных в play-by-play")
|
||||
stop_event.wait(TIMEOUT_DATA_OFF)
|
||||
continue
|
||||
|
||||
@@ -2310,7 +2310,7 @@ def Play_By_Play(data: dict, stop_event: threading.Event) -> None:
|
||||
|
||||
df_goals = df[df["play"].isin([1, 2, 3])].copy()
|
||||
if df_goals.empty:
|
||||
logger.debug("нет данных о голах в play-by-play")
|
||||
logger.warning("нет данных о голах в play-by-play")
|
||||
stop_event.wait(TIMEOUT_DATA_OFF)
|
||||
continue
|
||||
|
||||
@@ -2415,7 +2415,7 @@ def Play_By_Play(data: dict, stop_event: threading.Event) -> None:
|
||||
filepath = os.path.join(directory, f"{host_prefix}play_by_play.json")
|
||||
|
||||
df_goals.to_json(filepath, orient="records", force_ascii=False, indent=4)
|
||||
logger.debug("Успешно положил данные об play-by-play в файл")
|
||||
logger.info("Успешно положил данные об play-by-play в файл")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в Play_By_Play: {e}", exc_info=True)
|
||||
@@ -2581,7 +2581,7 @@ def Standing_func(data: dict, stop_event: threading.Event) -> None:
|
||||
force_ascii=False,
|
||||
indent=4,
|
||||
)
|
||||
logger.debug("Standings data saved successfully.")
|
||||
logger.info("Standings data saved successfully.")
|
||||
elif "playoffPairs" in item and item["playoffPairs"] != []:
|
||||
standings_temp = item["playoffPairs"]
|
||||
df = pd.json_normalize(standings_temp)
|
||||
@@ -2598,7 +2598,7 @@ def Standing_func(data: dict, stop_event: threading.Event) -> None:
|
||||
force_ascii=False,
|
||||
indent=4,
|
||||
)
|
||||
logger.debug("Standings data saved successfully.")
|
||||
logger.info("Standings data saved successfully.")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Ошибка в турнирном положении: {e}")
|
||||
|
||||
@@ -303,7 +303,10 @@ def load_data_from_json(filepath):
|
||||
directory = FOLDER_JSON
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
filepath_full = os.path.join(directory, f"{filepath}.json")
|
||||
print(filepath_full)
|
||||
|
||||
# print(filepath)
|
||||
# print(filepath_full)
|
||||
|
||||
# вычисление ключа
|
||||
# ip = get_ip_address()
|
||||
# host = ip_check.get(ip, {}).get("host") or ""
|
||||
|
||||
Reference in New Issue
Block a user