f20080305d
Определение специфических рекомендаций (матрица профилей §8):
1. Ж/д слой (закрыт мёртвый railway ×2.5 у РАС):
- /api/v1/water/{case_id} отдаёт railway=rail как LineString
(без service/industrial/military веток), кэш общий v2;
- railway_warning «перекрыть/проверить немедленно» по профилям;
- SearchMap: Polyline слой ж/д (тёмно-красный), счётчики 💧/🚂.
2. cant_swim → профиль не_умеет_плавать (water ×3.0, без изменения
радиуса, critical_warning «обследовать водоёмы НЕМЕДЛЕННО»):
- раньше чекбокс влиял только на текст, в скоринге был пробел;
- derive в analyze._derive_profiles — работает и для closed_cases.
3. unmodeled_profiles: ДЦП/слабое зрение/слух — честная пометка
«вне поведенческой модели» с пояснением (vector_tasks B12:
профили без аналога не выдавать за учтённые); блок на фронте
в карточке здоровья.
Площадь воды: сферический эксцесс, проверен на квадрате 53° (744017 м²
vs 743272 точного). Тесты: 202 passed (новый test_cant_swim_profile).
66 lines
2.2 KiB
Python
66 lines
2.2 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from starlette._utils import is_async_callable
|
|
from starlette.concurrency import run_in_threadpool
|
|
from starlette.exceptions import HTTPException
|
|
from starlette.requests import Request
|
|
from starlette.types import ASGIApp, ExceptionHandler, Message, Receive, Scope, Send
|
|
from starlette.websockets import WebSocket
|
|
|
|
ExceptionHandlers = dict[Any, ExceptionHandler]
|
|
StatusHandlers = dict[int, ExceptionHandler]
|
|
|
|
|
|
def _lookup_exception_handler(exc_handlers: ExceptionHandlers, exc: Exception) -> ExceptionHandler | None:
|
|
for cls in type(exc).__mro__:
|
|
if cls in exc_handlers:
|
|
return exc_handlers[cls]
|
|
return None
|
|
|
|
|
|
def wrap_app_handling_exceptions(app: ASGIApp, conn: Request | WebSocket) -> ASGIApp:
|
|
exception_handlers: ExceptionHandlers
|
|
status_handlers: StatusHandlers
|
|
try:
|
|
exception_handlers, status_handlers = conn.scope["starlette.exception_handlers"]
|
|
except KeyError:
|
|
exception_handlers, status_handlers = {}, {}
|
|
|
|
async def wrapped_app(scope: Scope, receive: Receive, send: Send) -> None:
|
|
response_started = False
|
|
|
|
async def sender(message: Message) -> None:
|
|
nonlocal response_started
|
|
|
|
if message["type"] == "http.response.start":
|
|
response_started = True
|
|
await send(message)
|
|
|
|
try:
|
|
await app(scope, receive, sender)
|
|
except Exception as exc:
|
|
handler = None
|
|
|
|
if isinstance(exc, HTTPException):
|
|
handler = status_handlers.get(exc.status_code)
|
|
|
|
if handler is None:
|
|
handler = _lookup_exception_handler(exception_handlers, exc)
|
|
|
|
if handler is None:
|
|
raise exc
|
|
|
|
if response_started:
|
|
raise RuntimeError("Caught handled exception, but response already started.") from exc
|
|
|
|
if is_async_callable(handler):
|
|
response = await handler(conn, exc) # type: ignore[arg-type]
|
|
else:
|
|
response = await run_in_threadpool(handler, conn, exc) # type: ignore[arg-type]
|
|
if response is not None:
|
|
await response(scope, receive, sender)
|
|
|
|
return wrapped_app
|