feat: schedule VK conversation messages
This commit is contained in:
1 parent
f7c5eb994e
commit
4590070bbc
9 files changed
+314
-2
No files matched your search
@@ -21,6 +21,7 @@ from .image_host import ImageHostClient
|
||||
from .identity import Identity, IdentityDirectory
|
||||
from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application
|
||||
from .google_sheets_export import GoogleSheetsExportService
|
||||
from .vk_scheduler import VkConversationStore, VkScheduler
|
||||
|
||||
"""
|
||||
Обработка VK-бота:
|
||||
@@ -853,6 +854,8 @@ class BelkiBot:
|
||||
self.application_store = ApplicationStore.from_environment()
|
||||
self.application_dialog = ApplicationDialog(identities, self.application_store)
|
||||
self.application_exporter = GoogleSheetsExportService(self.application_store)
|
||||
self.conversation_store = VkConversationStore.from_environment()
|
||||
self.scheduler = VkScheduler(self.conversation_store, self.client.send)
|
||||
|
||||
def response_for_text(self, text: str) -> str:
|
||||
"""Обработка текстового сообщения и возврат ответа."""
|
||||
@@ -874,6 +877,14 @@ class BelkiBot:
|
||||
return
|
||||
message = event.get("object", {}).get("message", event.get("object", {}))
|
||||
peer_id = message.get("peer_id")
|
||||
action = (message.get("action") or {}).get("type")
|
||||
if peer_id and int(peer_id) >= 2_000_000_000:
|
||||
chat_id = int(peer_id) - 2_000_000_000
|
||||
if action in {"chat_invite_user", "chat_invite_user_by_link"}:
|
||||
self.conversation_store.upsert_conversation(peer_id=int(peer_id), chat_id=chat_id,
|
||||
title=(message.get("chat_settings") or {}).get("title"), invited_by=message.get("from_id"))
|
||||
elif action in {"chat_kick_user", "chat_leave_user"}:
|
||||
self.conversation_store.mark_removed(int(peer_id), action)
|
||||
sender_id = message.get("from_id", message.get("sender_id", peer_id))
|
||||
text = self._button_text(message) or message.get("text", "")
|
||||
if peer_id is not None:
|
||||
@@ -963,6 +974,7 @@ class BelkiBot:
|
||||
self.application_exporter.sync_pending()
|
||||
time.sleep(15)
|
||||
threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start()
|
||||
threading.Thread(target=self.scheduler.run_forever, name="belki-vk-scheduler", daemon=True).start()
|
||||
for event in self.events():
|
||||
self.handle_event(event)
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""VK conversation registry and idempotent message scheduler."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
from typing import Any, Callable
|
||||
|
||||
MOSCOW = "Europe/Moscow"
|
||||
|
||||
|
||||
def conversation_peer_id(chat_id: int) -> int:
|
||||
"""Convert VK chat id (1-based) to the conversation peer id."""
|
||||
value = int(chat_id)
|
||||
if value <= 0:
|
||||
raise ValueError("chat_id должен быть положительным")
|
||||
return 2_000_000_000 + value
|
||||
|
||||
|
||||
def parse_schedule(*, times: list[str], weekdays: list[int] | None = None,
|
||||
timezone_name: str = MOSCOW) -> tuple[list[str], list[int], str]:
|
||||
"""Validate fixed HH:MM times and ISO weekdays (1=Mon..7=Sun)."""
|
||||
try:
|
||||
ZoneInfo(timezone_name)
|
||||
except Exception as exc:
|
||||
raise ValueError("Неизвестный часовой пояс") from exc
|
||||
clean_times = sorted(set(str(value).strip() for value in times))
|
||||
if not clean_times:
|
||||
raise ValueError("Укажите хотя бы одно время")
|
||||
for value in clean_times:
|
||||
if len(value) != 5 or value[2] != ":":
|
||||
raise ValueError("Время должно быть в формате HH:MM")
|
||||
hour, minute = value.split(":")
|
||||
if not (hour.isdigit() and minute.isdigit() and 0 <= int(hour) <= 23 and 0 <= int(minute) <= 59):
|
||||
raise ValueError("Время должно быть в формате HH:MM")
|
||||
days = sorted(set(int(day) for day in (weekdays or [1, 2, 3, 4, 5, 6, 7])))
|
||||
if not days or any(day < 1 or day > 7 for day in days):
|
||||
raise ValueError("Дни недели должны быть от 1 до 7")
|
||||
return clean_times, days, timezone_name
|
||||
|
||||
|
||||
class VkConversationStore:
|
||||
"""Persistence for conversations, templates, schedules and delivery history."""
|
||||
|
||||
def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None:
|
||||
self.database_url = database_url or ""
|
||||
self.sqlite_path = Path(sqlite_path or os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3"))
|
||||
self._postgres = self.database_url.startswith(("postgres://", "postgresql://"))
|
||||
if self._postgres:
|
||||
import psycopg
|
||||
self._psycopg = psycopg
|
||||
self._ensure_schema()
|
||||
else:
|
||||
self.sqlite_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._ensure_schema()
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls) -> "VkConversationStore":
|
||||
return cls(os.getenv("BELKI_DATABASE_URL"), os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3"))
|
||||
|
||||
def _ensure_schema(self) -> None:
|
||||
statements = [
|
||||
"""CREATE TABLE IF NOT EXISTS vk_conversations (
|
||||
peer_id BIGINT PRIMARY KEY, chat_id BIGINT NOT NULL, title TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'active', mailing_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
added_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, invited_by BIGINT,
|
||||
removed_at TEXT, removal_reason TEXT, last_success_at TEXT, last_error TEXT)""",
|
||||
"""CREATE TABLE IF NOT EXISTS vk_message_templates (
|
||||
id INTEGER PRIMARY KEY, name TEXT NOT NULL, text TEXT NOT NULL,
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
starts_on TEXT, ends_on TEXT)""",
|
||||
"""CREATE TABLE IF NOT EXISTS vk_schedules (
|
||||
id INTEGER PRIMARY KEY, template_id INTEGER NOT NULL, peer_id BIGINT NOT NULL,
|
||||
times_json TEXT NOT NULL, weekdays_json TEXT NOT NULL, timezone TEXT NOT NULL DEFAULT 'Europe/Moscow',
|
||||
active BOOLEAN NOT NULL DEFAULT FALSE, starts_on TEXT, ends_on TEXT,
|
||||
FOREIGN KEY(template_id) REFERENCES vk_message_templates(id),
|
||||
FOREIGN KEY(peer_id) REFERENCES vk_conversations(peer_id))""",
|
||||
"""CREATE TABLE IF NOT EXISTS vk_delivery_attempts (
|
||||
id INTEGER PRIMARY KEY, schedule_id INTEGER NOT NULL, planned_for TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending', attempted_at TEXT, attempts INTEGER NOT NULL DEFAULT 0,
|
||||
vk_result TEXT, error TEXT, UNIQUE(schedule_id, planned_for))""",
|
||||
]
|
||||
if self._postgres:
|
||||
with self._psycopg.connect(self.database_url) as conn:
|
||||
for statement in statements:
|
||||
conn.execute(statement.replace("INTEGER PRIMARY KEY", "BIGSERIAL PRIMARY KEY"))
|
||||
else:
|
||||
with sqlite3.connect(self.sqlite_path) as conn:
|
||||
for statement in statements:
|
||||
conn.execute(statement)
|
||||
|
||||
def _execute(self, sql: str, params: tuple[Any, ...] = (), *, fetch: bool = False) -> list[tuple] | None:
|
||||
if self._postgres:
|
||||
with self._psycopg.connect(self.database_url) as conn:
|
||||
cur = conn.execute(sql.replace("?", "%s"), params)
|
||||
return cur.fetchall() if fetch else None
|
||||
with sqlite3.connect(self.sqlite_path) as conn:
|
||||
cur = conn.execute(sql, params)
|
||||
return cur.fetchall() if fetch else None
|
||||
|
||||
def upsert_conversation(self, *, peer_id: int, chat_id: int, title: str | None = None, invited_by: int | None = None) -> dict:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
if self._postgres:
|
||||
self._execute("""INSERT INTO vk_conversations(peer_id,chat_id,title,status,mailing_enabled,added_at,invited_by)
|
||||
VALUES(?,?,?, 'active',FALSE,?,?) ON CONFLICT(peer_id) DO UPDATE SET title=COALESCE(EXCLUDED.title,vk_conversations.title), status='active', removed_at=NULL, removal_reason=NULL, invited_by=COALESCE(EXCLUDED.invited_by,vk_conversations.invited_by)""", (peer_id, chat_id, title, now, invited_by))
|
||||
else:
|
||||
self._execute("""INSERT INTO vk_conversations(peer_id,chat_id,title,status,mailing_enabled,added_at,invited_by) VALUES(?,?,?,'active',0,?,?)
|
||||
ON CONFLICT(peer_id) DO UPDATE SET title=COALESCE(excluded.title,title), status='active', removed_at=NULL, removal_reason=NULL, invited_by=COALESCE(excluded.invited_by,invited_by)""", (peer_id, chat_id, title, now, invited_by))
|
||||
return self.get_conversation(peer_id) or {}
|
||||
|
||||
def mark_removed(self, peer_id: int, reason: str) -> None:
|
||||
self._execute("UPDATE vk_conversations SET status='bot_removed', mailing_enabled=FALSE, removed_at=?, removal_reason=? WHERE peer_id=?", (datetime.now(timezone.utc).isoformat(), reason[:500], peer_id))
|
||||
|
||||
def get_conversation(self, peer_id: int) -> dict | None:
|
||||
rows = self._execute("SELECT peer_id,chat_id,title,status,mailing_enabled,added_at,invited_by,removed_at,removal_reason,last_success_at,last_error FROM vk_conversations WHERE peer_id=?", (peer_id,), fetch=True) or []
|
||||
return self._conversation_row(rows[0]) if rows else None
|
||||
|
||||
def list_conversations(self) -> list[dict]:
|
||||
rows = self._execute("SELECT peer_id,chat_id,title,status,mailing_enabled,added_at,invited_by,removed_at,removal_reason,last_success_at,last_error FROM vk_conversations ORDER BY added_at DESC", fetch=True) or []
|
||||
return [self._conversation_row(row) for row in rows]
|
||||
|
||||
@staticmethod
|
||||
def _conversation_row(row: tuple) -> dict:
|
||||
keys = ("peer_id", "chat_id", "title", "status", "mailing_enabled", "added_at", "invited_by", "removed_at", "removal_reason", "last_success_at", "last_error")
|
||||
return dict(zip(keys, row))
|
||||
|
||||
def create_template(self, name: str, text: str, *, active: bool = True, starts_on: str | None = None, ends_on: str | None = None) -> int:
|
||||
if not text.strip() or len(text) > 4096: raise ValueError("Текст шаблона должен быть от 1 до 4096 символов")
|
||||
rows = self._execute("INSERT INTO vk_message_templates(name,text,active,starts_on,ends_on) VALUES(?,?,?,?,?) RETURNING id", (name.strip() or "Без названия", text.strip(), active, starts_on, ends_on), fetch=True)
|
||||
return int(rows[0][0]) if rows else 0
|
||||
|
||||
def list_templates(self) -> list[dict]:
|
||||
rows = self._execute("SELECT id,name,text,active,starts_on,ends_on,created_at FROM vk_message_templates ORDER BY id DESC", fetch=True) or []
|
||||
return [dict(zip(("id","name","text","active","starts_on","ends_on","created_at"), row)) for row in rows]
|
||||
|
||||
def create_schedule(self, *, template_id: int, peer_id: int, times: list[str], weekdays: list[int] | None = None, timezone_name: str = MOSCOW, active: bool = False, starts_on: str | None = None, ends_on: str | None = None) -> int:
|
||||
clean_times, days, zone = parse_schedule(times=times, weekdays=weekdays, timezone_name=timezone_name)
|
||||
rows = self._execute("INSERT INTO vk_schedules(template_id,peer_id,times_json,weekdays_json,timezone,active,starts_on,ends_on) VALUES(?,?,?,?,?,?,?,?) RETURNING id", (template_id, peer_id, json.dumps(clean_times), json.dumps(days), zone, active, starts_on, ends_on), fetch=True)
|
||||
return int(rows[0][0]) if rows else 0
|
||||
|
||||
def list_schedules(self) -> list[dict]:
|
||||
rows = self._execute("SELECT id,template_id,peer_id,times_json,weekdays_json,timezone,active,starts_on,ends_on FROM vk_schedules ORDER BY id DESC", fetch=True) or []
|
||||
keys = ("id","template_id","peer_id","times","weekdays","timezone","active","starts_on","ends_on")
|
||||
return [{**dict(zip(keys, row[:3] + (json.loads(row[3]), json.loads(row[4])) + row[5:]))} for row in rows]
|
||||
|
||||
def claim_delivery(self, schedule_id: int, planned_for: str) -> bool:
|
||||
try:
|
||||
self._execute("INSERT INTO vk_delivery_attempts(schedule_id,planned_for) VALUES(?,?)", (schedule_id, planned_for))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def finish_delivery(self, schedule_id: int, planned_for: str, *, success: bool, result: Any = None, error: str | None = None) -> None:
|
||||
self._execute("UPDATE vk_delivery_attempts SET status=?,attempted_at=?,attempts=attempts+1,vk_result=?,error=? WHERE schedule_id=? AND planned_for=?", ("sent" if success else "failed", datetime.now(timezone.utc).isoformat(), json.dumps(result, ensure_ascii=False) if result is not None else None, error[:1000] if error else None, schedule_id, planned_for))
|
||||
if success:
|
||||
self._execute("UPDATE vk_conversations SET last_success_at=?,last_error=NULL WHERE peer_id=(SELECT peer_id FROM vk_schedules WHERE id=?)", (datetime.now(timezone.utc).isoformat(), schedule_id))
|
||||
else:
|
||||
self._execute("UPDATE vk_conversations SET last_error=? WHERE peer_id=(SELECT peer_id FROM vk_schedules WHERE id=?)", (error[:1000] if error else "Ошибка VK", schedule_id))
|
||||
|
||||
|
||||
class VkScheduler:
|
||||
def __init__(self, store: VkConversationStore, send: Callable[[int, str], Any], *, interval: float = 20.0) -> None:
|
||||
self.store, self.send, self.interval = store, send, interval
|
||||
|
||||
@staticmethod
|
||||
def planned_slot(schedule: dict, now: datetime | None = None) -> datetime | None:
|
||||
zone = ZoneInfo(schedule.get("timezone", MOSCOW)); local = (now or datetime.now(timezone.utc)).astimezone(zone).replace(second=0, microsecond=0)
|
||||
if local.isoweekday() not in schedule.get("weekdays", [1,2,3,4,5,6,7]): return None
|
||||
candidates = [local.replace(hour=int(t[:2]), minute=int(t[3:])) for t in schedule.get("times", [])]
|
||||
past = [candidate for candidate in candidates if candidate <= local]
|
||||
return max(past) if past else None
|
||||
|
||||
def run_once(self, now: datetime | None = None) -> int:
|
||||
sent = 0
|
||||
for schedule in self.store.list_schedules():
|
||||
if not schedule.get("active"): continue
|
||||
slot = self.planned_slot(schedule, now)
|
||||
if slot is None or (schedule.get("starts_on") and slot.date().isoformat() < schedule["starts_on"]) or (schedule.get("ends_on") and slot.date().isoformat() > schedule["ends_on"]): continue
|
||||
planned_for = slot.astimezone(timezone.utc).isoformat()
|
||||
if not self.store.claim_delivery(schedule["id"], planned_for): continue
|
||||
template = next((item for item in self.store.list_templates() if item["id"] == schedule["template_id"] and item.get("active")), None)
|
||||
conversation = self.store.get_conversation(schedule["peer_id"])
|
||||
if not template or not conversation or conversation.get("status") != "active" or not conversation.get("mailing_enabled"):
|
||||
self.store.finish_delivery(schedule["id"], planned_for, success=False, error="Рассылка отключена или беседа недоступна")
|
||||
continue
|
||||
try:
|
||||
result = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
result = self.send(int(schedule["peer_id"]), template["text"])
|
||||
break
|
||||
except (OSError, TimeoutError) as exc:
|
||||
if attempt == 2:
|
||||
raise
|
||||
time.sleep(0.25 * (2 ** attempt))
|
||||
self.store.finish_delivery(schedule["id"], planned_for, success=True, result=result); sent += 1
|
||||
except Exception as exc:
|
||||
self.store.finish_delivery(schedule["id"], planned_for, success=False, error=str(exc))
|
||||
return sent
|
||||
|
||||
def run_forever(self) -> None:
|
||||
while True:
|
||||
try: self.run_once()
|
||||
except Exception: pass
|
||||
time.sleep(self.interval)
|
||||
+46
-1
@@ -22,6 +22,7 @@ from .belki.identity import IdentityDirectory
|
||||
from .belki.image_host import ImageHostClient, ImageHostError
|
||||
from .belki.xlsx_export import build_xlsx
|
||||
from .sudoku import SudokuError, SudokuStore
|
||||
from .belki.vk_scheduler import VkConversationStore
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -30,6 +31,7 @@ _HISTORY_STORE: CalculationStore | None = None
|
||||
_IDENTITY_DIR: IdentityDirectory | None = None
|
||||
_APPLICATION_STORE: ApplicationStore | None = None
|
||||
_SUDOKU_STORE: SudokuStore | None = None
|
||||
_VK_CONVERSATION_STORE: VkConversationStore | None = None
|
||||
_ADMIN_SESSIONS: dict[str, float] = {}
|
||||
_ADMIN_SESSIONS_LOCK = threading.Lock()
|
||||
_ISSUED_WEB_UPLOAD_URLS: dict[str, float] = {}
|
||||
@@ -189,6 +191,13 @@ def sudoku_store() -> SudokuStore:
|
||||
return _SUDOKU_STORE
|
||||
|
||||
|
||||
def vk_conversation_store() -> VkConversationStore:
|
||||
global _VK_CONVERSATION_STORE
|
||||
if _VK_CONVERSATION_STORE is None:
|
||||
_VK_CONVERSATION_STORE = VkConversationStore.from_environment()
|
||||
return _VK_CONVERSATION_STORE
|
||||
|
||||
|
||||
def public_sudoku_game(game: dict) -> dict:
|
||||
"""Keep the answer key on the server while returning a playable game."""
|
||||
return {key: value for key, value in game.items() if key != "solution"}
|
||||
@@ -441,6 +450,18 @@ class Handler(BaseHTTPRequestHandler):
|
||||
rows = [[item["id"], datetime.fromisoformat(str(item["created_at"]).replace("Z", "+00:00")), item["status"], item["source"], item["application"].get("type", ""), item["application"].get("name", ""), item["application"].get("character_id")] for item in records]
|
||||
self._xlsx("belki-applications.xlsx", build_xlsx(sheet_name="Заявки", headers=["ID", "Создана (UTC+3)", "Статус", "Источник", "Тип", "Имя", "ID персонажа"], rows=rows, display_timezone=WEB_TIMEZONE))
|
||||
return
|
||||
if path == "/api/admin/vk/conversations":
|
||||
if not self._admin_authorized(): return
|
||||
self._json(200, {"items": vk_conversation_store().list_conversations()})
|
||||
return
|
||||
if path == "/api/admin/vk/templates":
|
||||
if not self._admin_authorized(): return
|
||||
self._json(200, {"items": vk_conversation_store().list_templates()})
|
||||
return
|
||||
if path == "/api/admin/vk/schedules":
|
||||
if not self._admin_authorized(): return
|
||||
self._json(200, {"items": vk_conversation_store().list_schedules()})
|
||||
return
|
||||
requested = unquote(path).lstrip("/")
|
||||
candidate = (WEB_ROOT / requested).resolve()
|
||||
if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents:
|
||||
@@ -483,7 +504,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
is_sudoku_create = parsed.path == "/api/sudoku/games"
|
||||
is_sudoku_regenerate = parsed.path.startswith("/api/sudoku/games/") and parsed.path.endswith("/regenerate")
|
||||
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/reports", "/api/inspect-bulk", "/api/resolve-identity",
|
||||
"/api/applications") and not is_sudoku_create and not is_sudoku_regenerate:
|
||||
"/api/applications", "/api/admin/vk/templates", "/api/admin/vk/schedules") and not is_sudoku_create and not is_sudoku_regenerate:
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
return
|
||||
try:
|
||||
@@ -546,6 +567,14 @@ class Handler(BaseHTTPRequestHandler):
|
||||
application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web")
|
||||
sync_application_exports()
|
||||
self._json(201, {"id": application_id, "status": "pending", "message": "Заявка отправлена на рассмотрение."})
|
||||
elif self.path == "/api/admin/vk/templates":
|
||||
if not self._admin_authorized(): return
|
||||
template_id = vk_conversation_store().create_template(str(payload.get("name", "")), str(payload.get("text", "")), active=bool(payload.get("active", True)), starts_on=payload.get("starts_on"), ends_on=payload.get("ends_on"))
|
||||
self._json(201, {"id": template_id})
|
||||
elif self.path == "/api/admin/vk/schedules":
|
||||
if not self._admin_authorized(): return
|
||||
schedule_id = vk_conversation_store().create_schedule(template_id=int(payload["template_id"]), peer_id=int(payload["peer_id"]), times=payload.get("times", []), weekdays=payload.get("weekdays"), timezone_name=str(payload.get("timezone", "Europe/Moscow")), active=bool(payload.get("active", False)), starts_on=payload.get("starts_on"), ends_on=payload.get("ends_on"))
|
||||
self._json(201, {"id": schedule_id})
|
||||
elif self.path == "/api/calculate":
|
||||
payload["attachments"] = validate_web_report_attachments(payload)
|
||||
self._json(200, calculate_payload(payload))
|
||||
@@ -599,6 +628,22 @@ class Handler(BaseHTTPRequestHandler):
|
||||
def do_PATCH(self) -> None: # noqa: N802
|
||||
"""Меняет статус новой заявки через PATCH API."""
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path.startswith("/api/admin/vk/conversations/") or parsed.path.startswith("/api/admin/vk/schedules/"):
|
||||
if not self._admin_authorized(): return
|
||||
try:
|
||||
payload = self._read_json_body()
|
||||
item_id = int(parsed.path.rsplit("/", 1)[1])
|
||||
store = vk_conversation_store()
|
||||
if "/conversations/" in parsed.path:
|
||||
store._execute("UPDATE vk_conversations SET mailing_enabled=? WHERE peer_id=?", (bool(payload.get("mailing_enabled")), item_id))
|
||||
item = store.get_conversation(item_id)
|
||||
else:
|
||||
store._execute("UPDATE vk_schedules SET active=? WHERE id=?", (bool(payload.get("active")), item_id))
|
||||
item = next((x for x in store.list_schedules() if x["id"] == item_id), None)
|
||||
if item is None: self._json(404, {"error": "Запись не найдена"})
|
||||
else: self._json(200, {"item": item})
|
||||
except (ValueError, ApiError) as exc: self._json(400, {"error": str(exc)})
|
||||
return
|
||||
prefix = "/api/admin/applications/"
|
||||
if not parsed.path.startswith(prefix):
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
|
||||
Reference in new issue
Block a user