Добавил:
omninoy
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:ЛР-8 / lab8_gigachat_auth
.py"""OAuth-токен GigaChat API (POST /api/v2/oauth)."""
from __future__ import annotations
import json
import os
import time
import uuid
from pathlib import Path
import requests
OAUTH_URL = "https://ngw.devices.sberbank.ru:9443/api/v2/oauth"
DEFAULT_SCOPE = "GIGACHAT_API_PERS"
SCRIPT_DIR = Path(__file__).resolve().parent
CREDENTIALS_FILE = SCRIPT_DIR / "gigachat_credentials.txt"
TOKEN_CACHE = SCRIPT_DIR / ".lab8_gigachat_token.json"
def _verify_ssl() -> bool:
return os.environ.get("GIGACHAT_VERIFY_SSL", "").lower() in ("1", "true", "yes")
def load_credentials() -> str:
key = os.environ.get("GIGACHAT_CREDENTIALS", "").strip()
if key:
return key
if CREDENTIALS_FILE.exists():
for line in CREDENTIALS_FILE.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#"):
return line
raise RuntimeError(
"Нет ключа авторизации GigaChat. Задайте GIGACHAT_CREDENTIALS "
f"или файл {CREDENTIALS_FILE.name} (одна строка — ключ из личного кабинета)."
)
def _save_cache(access_token: str, expires_at: float) -> None:
TOKEN_CACHE.write_text(
json.dumps({"access_token": access_token, "expires_at": expires_at}),
encoding="utf-8",
)
def _load_cache() -> tuple[str, float] | None:
if not TOKEN_CACHE.exists():
return None
try:
data = json.loads(TOKEN_CACHE.read_text(encoding="utf-8"))
token = data.get("access_token", "")
expires_at = float(data.get("expires_at", 0))
if token and expires_at > time.time() + 30:
return token, expires_at
except (json.JSONDecodeError, TypeError, ValueError):
pass
return None
def fetch_access_token(credentials: str | None = None, scope: str = DEFAULT_SCOPE) -> str:
"""Получить Bearer-токен (с кэшем в .lab8_gigachat_token.json)."""
cached = _load_cache()
if cached:
return cached[0]
if credentials is None:
credentials = load_credentials()
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"RqUID": str(uuid.uuid4()),
"Authorization": f"Basic {credentials}",
}
response = requests.post(
OAUTH_URL,
headers=headers,
data={"scope": scope},
timeout=60,
verify=_verify_ssl(),
)
response.raise_for_status()
payload = response.json()
token = payload["access_token"]
expires_at = float(payload.get("expires_at", time.time() + 1800))
_save_cache(token, expires_at)
return token
Соседние файлы в папке ЛР-8
