коммит
This commit is contained in:
100
get_data.py
100
get_data.py
@@ -1,8 +1,4 @@
|
||||
<<<<<<< HEAD
|
||||
from fastapi import FastAPI, HTTPException, Query
|
||||
=======
|
||||
from fastapi import FastAPI, HTTPException, Query, Request
|
||||
>>>>>>> c60caaa8aaad763cf7605dcd2c4502b8dfc3be84
|
||||
from fastapi.responses import Response, JSONResponse, HTMLResponse, StreamingResponse
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
import pandas as pd
|
||||
@@ -19,10 +15,7 @@ import nasio
|
||||
import logging
|
||||
import logging.config
|
||||
import platform
|
||||
<<<<<<< HEAD
|
||||
=======
|
||||
import json
|
||||
>>>>>>> c60caaa8aaad763cf7605dcd2c4502b8dfc3be84
|
||||
from pprint import pprint
|
||||
|
||||
|
||||
@@ -36,18 +29,7 @@ _latest_lock = Lock()
|
||||
_stop_event = Event()
|
||||
_worker_thread: Thread | None = None
|
||||
|
||||
<<<<<<< HEAD
|
||||
# Загружаем переменные из .env
|
||||
if load_dotenv(dotenv_path="/mnt/khl/.env", verbose=True):
|
||||
print("Добавить в лог что был найден файл окружения!!")
|
||||
pass
|
||||
else:
|
||||
load_dotenv()
|
||||
print("Добавить в лог что не был найден файл окружения!!")
|
||||
|
||||
=======
|
||||
pprint(f"Локальный файл окружения ={load_dotenv(verbose=True)}")
|
||||
>>>>>>> c60caaa8aaad763cf7605dcd2c4502b8dfc3be84
|
||||
api_user = os.getenv("API_USER")
|
||||
api_pass = os.getenv("API_PASS")
|
||||
league = os.getenv("LEAGUE")
|
||||
@@ -749,11 +731,6 @@ def _norm_name(s: str | None) -> str:
|
||||
return ""
|
||||
return str(s).strip().casefold()
|
||||
|
||||
<<<<<<< HEAD
|
||||
|
||||
@app.get("/info")
|
||||
def info():
|
||||
=======
|
||||
def _load_buf():
|
||||
buf = nasio.load_bio(user=USER, password=PASSWORD,
|
||||
nas_ip=SERVER_NAME, nas_port="443", path=PATH)
|
||||
@@ -764,7 +741,6 @@ def _load_buf():
|
||||
|
||||
@app.get("/info")
|
||||
async def info(format: str = "xlsx", sheet: str = "TEAMS"):
|
||||
>>>>>>> c60caaa8aaad763cf7605dcd2c4502b8dfc3be84
|
||||
# 1) Проверяем, выбран ли матч
|
||||
global current_season
|
||||
if not selected_game_id:
|
||||
@@ -793,81 +769,6 @@ async def info(format: str = "xlsx", sheet: str = "TEAMS"):
|
||||
away_name = str(row.get("visitorName_en", "")).strip()
|
||||
|
||||
# 3) Подтягиваем справочник команд из Excel (лист TEAMS)
|
||||
<<<<<<< HEAD
|
||||
try:
|
||||
binary_bytes: bytes = nasio.load_bio(
|
||||
user=USER,
|
||||
password=PASSWORD,
|
||||
nas_ip=SERVER_NAME,
|
||||
nas_port="443",
|
||||
path=PATH,
|
||||
# sheet="TEAMS"
|
||||
)
|
||||
buf = io.BytesIO(binary_bytes)
|
||||
headers = {
|
||||
"Content-Length": str(len(binary_bytes)),
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
"Pragma": "no-cache",
|
||||
# можно подсунуть имя файла (если парсеру это важно)
|
||||
"Content-Disposition": 'inline; filename="MATCH.xlsm"',
|
||||
}
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.ms-excel.sheet.macroEnabled.12",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
# Оставляем только полезные поля (подгони под свой файл)
|
||||
keep = ["Team", "Logo", "Short", "HexPodl", "HexBase", "HexText"]
|
||||
keep = [c for c in keep if c in teams_df.columns]
|
||||
teams_df = teams_df.loc[:, keep].copy()
|
||||
|
||||
# 4) Нормализованные ключи для джоина по имени
|
||||
teams_df["__key"] = teams_df["Team"].apply(_norm_name)
|
||||
|
||||
def _pick_team_info(name: str) -> dict:
|
||||
key = _norm_name(name)
|
||||
hit = teams_df.loc[teams_df["__key"] == key]
|
||||
if hit.empty:
|
||||
# не нашли точное совпадение — вернём только название
|
||||
return {"Team": name}
|
||||
rec = hit.iloc[0].to_dict()
|
||||
rec.pop("__key", None)
|
||||
# заменим NaN/inf на None, чтобы JSON не падал
|
||||
for k, v in list(rec.items()):
|
||||
if pd.isna(v) or v in (np.inf, -np.inf):
|
||||
rec[k] = None
|
||||
return rec
|
||||
|
||||
home_info = _pick_team_info(home_name)
|
||||
away_info = _pick_team_info(away_name)
|
||||
date_obj = datetime.strptime(row.get("datetime_str", ""), "%d.%m.%Y %H:%M")
|
||||
try:
|
||||
full_format = date_obj.strftime("%B %-d, %Y")
|
||||
except ValueError:
|
||||
full_format = date_obj.strftime("%B %#d, %Y")
|
||||
|
||||
payload = [
|
||||
{
|
||||
"selected_id": int(selected_game_id),
|
||||
"tournament_id": (
|
||||
int(current_tournament_id) if current_tournament_id else None
|
||||
),
|
||||
"datetime": str(full_format),
|
||||
"arena": str(row.get("arena_en", "")),
|
||||
"arena_city": str(row.get("arena_city_en", "")),
|
||||
"home": home_info,
|
||||
"home_city": str(row.get("homeCity_en", "")),
|
||||
"away": away_info,
|
||||
"away_city": str(row.get("visitorCity_en", "")),
|
||||
"season": current_season,
|
||||
}
|
||||
]
|
||||
|
||||
return JSONResponse(content=payload)
|
||||
except Exception as ex:
|
||||
pprint(ex)
|
||||
=======
|
||||
src = _load_buf()
|
||||
|
||||
if format == "xlsx":
|
||||
@@ -969,7 +870,6 @@ async def info(format: str = "xlsx", sheet: str = "TEAMS"):
|
||||
# return JSONResponse(content=payload)
|
||||
# except Exception as ex:
|
||||
# pprint(ex)
|
||||
>>>>>>> c60caaa8aaad763cf7605dcd2c4502b8dfc3be84
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user