docs: document HTTP request handlers
This commit is contained in:
1 parent
df4b864d1d
commit
a1dee5ae57
1 file changed
+10
+10
@@ -183,6 +183,7 @@ def application_store() -> ApplicationStore:
|
|||||||
|
|
||||||
|
|
||||||
def sync_application_exports() -> int:
|
def sync_application_exports() -> int:
|
||||||
|
"""Отправляет накопленные outbox-события в настроенный внешний экспорт."""
|
||||||
"""No-op until the explicitly disabled Google export is configured."""
|
"""No-op until the explicitly disabled Google export is configured."""
|
||||||
return GoogleSheetsExportService(application_store()).sync_pending()
|
return GoogleSheetsExportService(application_store()).sync_pending()
|
||||||
|
|
||||||
@@ -260,10 +261,12 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self.wfile.write(encoded)
|
self.wfile.write(encoded)
|
||||||
|
|
||||||
def _admin_cookie(self, token: str) -> str:
|
def _admin_cookie(self, token: str) -> str:
|
||||||
|
"""Формирует безопасный cookie заголовок для административного токена."""
|
||||||
secure = "; Secure" if self.headers.get("X-Forwarded-Proto", "") == "https" else ""
|
secure = "; Secure" if self.headers.get("X-Forwarded-Proto", "") == "https" else ""
|
||||||
return f"belki_admin_session={token}; Path=/; Max-Age={ADMIN_SESSION_TTL_SECONDS}; HttpOnly; SameSite=Lax{secure}"
|
return f"belki_admin_session={token}; Path=/; Max-Age={ADMIN_SESSION_TTL_SECONDS}; HttpOnly; SameSite=Lax{secure}"
|
||||||
|
|
||||||
def _serve_admin_updates(self) -> None:
|
def _serve_admin_updates(self) -> None:
|
||||||
|
"""Возвращает административную страницу после проверки доступа."""
|
||||||
if not self._admin_session_authorized():
|
if not self._admin_session_authorized():
|
||||||
self._json(401, {"error": "Требуется авторизация"})
|
self._json(401, {"error": "Требуется авторизация"})
|
||||||
return
|
return
|
||||||
@@ -294,6 +297,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
release_admin_update_slot()
|
release_admin_update_slot()
|
||||||
|
|
||||||
def do_GET(self) -> None: # noqa: N802
|
def do_GET(self) -> None: # noqa: N802
|
||||||
|
"""Маршрутизирует GET-запросы к API, админке или статическим файлам."""
|
||||||
path = urlparse(self.path).path
|
path = urlparse(self.path).path
|
||||||
if path in ("/health", "/api/health"):
|
if path in ("/health", "/api/health"):
|
||||||
self._json(200, {"status": "ok"})
|
self._json(200, {"status": "ok"})
|
||||||
@@ -340,6 +344,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self._json(404, {"error": "Не найдено"})
|
self._json(404, {"error": "Не найдено"})
|
||||||
|
|
||||||
def _file(self, path: Path) -> None:
|
def _file(self, path: Path) -> None:
|
||||||
|
"""Отдаёт существующий статический файл с подходящим MIME-типом."""
|
||||||
content = path.read_bytes()
|
content = path.read_bytes()
|
||||||
self.send_response(200)
|
self.send_response(200)
|
||||||
self.send_header("Content-Type", mimetypes.guess_type(path.name)[0] or "application/octet-stream")
|
self.send_header("Content-Type", mimetypes.guess_type(path.name)[0] or "application/octet-stream")
|
||||||
@@ -348,6 +353,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self.wfile.write(content)
|
self.wfile.write(content)
|
||||||
|
|
||||||
def _read_json_body(self) -> dict:
|
def _read_json_body(self) -> dict:
|
||||||
|
"""Читает JSON-тело запроса с ограничением размера и проверкой объекта."""
|
||||||
"""Read a bounded JSON request before passing it to public handlers."""
|
"""Read a bounded JSON request before passing it to public handlers."""
|
||||||
content_type = self.headers.get("Content-Type", "")
|
content_type = self.headers.get("Content-Type", "")
|
||||||
if not content_type.lower().startswith("application/json"):
|
if not content_type.lower().startswith("application/json"):
|
||||||
@@ -367,6 +373,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
return payload
|
return payload
|
||||||
|
|
||||||
def do_POST(self) -> None: # noqa: N802
|
def do_POST(self) -> None: # noqa: N802
|
||||||
|
"""Обрабатывает вход, авторизацию и создание заявок через POST API."""
|
||||||
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
|
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
|
||||||
"/api/applications"):
|
"/api/applications"):
|
||||||
self._json(404, {"error": "Не найдено"})
|
self._json(404, {"error": "Не найдено"})
|
||||||
@@ -436,6 +443,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self._json(500, {"error": "Внутренняя ошибка калькулятора"})
|
self._json(500, {"error": "Внутренняя ошибка калькулятора"})
|
||||||
|
|
||||||
def do_DELETE(self) -> None: # noqa: N802
|
def do_DELETE(self) -> None: # noqa: N802
|
||||||
|
"""Удаляет заявку после проверки административной авторизации."""
|
||||||
parsed = urlparse(self.path)
|
parsed = urlparse(self.path)
|
||||||
prefix = "/api/admin/calculations/"
|
prefix = "/api/admin/calculations/"
|
||||||
if not parsed.path.startswith(prefix):
|
if not parsed.path.startswith(prefix):
|
||||||
@@ -456,6 +464,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self._json(200, {"deleted": calculation_id})
|
self._json(200, {"deleted": calculation_id})
|
||||||
|
|
||||||
def do_PATCH(self) -> None: # noqa: N802
|
def do_PATCH(self) -> None: # noqa: N802
|
||||||
|
"""Принимает заявку и запускает уведомление через PATCH API."""
|
||||||
parsed = urlparse(self.path)
|
parsed = urlparse(self.path)
|
||||||
prefix = "/api/admin/applications/"
|
prefix = "/api/admin/applications/"
|
||||||
if not parsed.path.startswith(prefix) or not parsed.path.endswith("/accept"):
|
if not parsed.path.startswith(prefix) or not parsed.path.endswith("/accept"):
|
||||||
@@ -476,6 +485,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self._json(200, {"item": application})
|
self._json(200, {"item": application})
|
||||||
|
|
||||||
def log_message(self, format: str, *args: object) -> None:
|
def log_message(self, format: str, *args: object) -> None:
|
||||||
|
"""Пишет стандартные HTTP-логи в настроенный логгер приложения."""
|
||||||
if os.getenv("BELKI_ACCESS_LOG", "0") == "1":
|
if os.getenv("BELKI_ACCESS_LOG", "0") == "1":
|
||||||
super().log_message(format, *args)
|
super().log_message(format, *args)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user