239 lines
5.8 KiB
Python
239 lines
5.8 KiB
Python
import json
|
||
import logging
|
||
import ssl
|
||
import urllib.request
|
||
from dataclasses import dataclass
|
||
|
||
from constance import config
|
||
from ninja import Schema
|
||
from ninja.errors import HttpError
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
DADATA_SUGGEST_URL = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address"
|
||
DADATA_TIMEOUT_SECONDS = 10
|
||
|
||
|
||
class DaDataDisabledError(HttpError):
|
||
def __init__(self, message: str = "Интеграция с DaData отключена"):
|
||
super().__init__(503, message)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class DaDataStreet:
|
||
value: str
|
||
fias_id: str
|
||
kladr_id: str
|
||
street: str
|
||
street_type: str
|
||
street_with_type: str
|
||
city: str
|
||
region_code: str
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class DaDataHouse:
|
||
value: str
|
||
fias_id: str
|
||
house: str
|
||
house_type: str
|
||
block: str
|
||
postal_code: str
|
||
street: str
|
||
city: str
|
||
region_code: str
|
||
block_type: str = ""
|
||
|
||
|
||
class DaDataStreetParams(Schema):
|
||
query: str = ""
|
||
region_code: str
|
||
city: str
|
||
limit: int = 20
|
||
|
||
|
||
class DaDataHouseParams(DaDataStreetParams):
|
||
street: str
|
||
|
||
|
||
class DaDataStreetOut(Schema):
|
||
value: str
|
||
fias_id: str
|
||
kladr_id: str
|
||
street: str
|
||
street_type: str
|
||
street_with_type: str
|
||
city: str
|
||
region_code: str
|
||
|
||
|
||
class DaDataHouseOut(Schema):
|
||
value: str
|
||
fias_id: str
|
||
house: str
|
||
house_type: str
|
||
block: str
|
||
postal_code: str
|
||
street: str
|
||
city: str
|
||
region_code: str
|
||
|
||
|
||
class DaDataStreetResponse(Schema):
|
||
count: int
|
||
items: list[DaDataStreetOut]
|
||
|
||
|
||
class DaDataHouseResponse(Schema):
|
||
count: int
|
||
items: list[DaDataHouseOut]
|
||
|
||
|
||
def dadata_token_or_none() -> str | None:
|
||
if not config.DADATA_IS_ENABLED:
|
||
return None
|
||
token = (config.DADATA_TOKEN or "").strip()
|
||
return token or None
|
||
|
||
|
||
def require_dadata() -> str:
|
||
if not config.DADATA_IS_ENABLED:
|
||
raise DaDataDisabledError()
|
||
token = (config.DADATA_TOKEN or "").strip()
|
||
if not token:
|
||
raise DaDataDisabledError("Не задан токен DaData")
|
||
return token
|
||
|
||
|
||
def suggest_streets(
|
||
*,
|
||
region_code: str,
|
||
city: str,
|
||
query: str,
|
||
limit: int,
|
||
) -> list[DaDataStreet]:
|
||
require_dadata()
|
||
return []
|
||
|
||
|
||
def house_suggest_payload(
|
||
*,
|
||
query: str,
|
||
limit: int,
|
||
region_code: str = "",
|
||
city: str = "",
|
||
street: str = "",
|
||
street_fias_id: str | None = None,
|
||
) -> dict:
|
||
location: dict[str, str] = {}
|
||
if street_fias_id:
|
||
location["street_fias_id"] = street_fias_id
|
||
else:
|
||
if region_code:
|
||
location["kladr_id"] = str(region_code).zfill(2)
|
||
if city:
|
||
location["city"] = city
|
||
if street:
|
||
location["street"] = street
|
||
payload = {
|
||
"query": query,
|
||
"count": min(max(limit, 1), 20),
|
||
"from_bound": {"value": "house"},
|
||
"to_bound": {"value": "house"},
|
||
}
|
||
if location:
|
||
payload["locations"] = [location]
|
||
return payload
|
||
|
||
|
||
def suggest_houses(
|
||
*,
|
||
region_code: str,
|
||
city: str,
|
||
street: str,
|
||
query: str,
|
||
limit: int,
|
||
street_fias_id: str | None = None,
|
||
) -> list[DaDataHouse]:
|
||
token = require_dadata()
|
||
payload = house_suggest_payload(
|
||
query=query,
|
||
limit=limit,
|
||
region_code=region_code,
|
||
city=city,
|
||
street=street,
|
||
street_fias_id=street_fias_id,
|
||
)
|
||
return parse_house_suggestions(_suggest_address(token, payload))
|
||
|
||
|
||
def parse_house_suggestions(suggestions: list) -> list[DaDataHouse]:
|
||
items: list[DaDataHouse] = []
|
||
for suggestion in suggestions:
|
||
if not isinstance(suggestion, dict):
|
||
continue
|
||
data = suggestion.get("data") or {}
|
||
if not isinstance(data, dict):
|
||
continue
|
||
fias_id = str(data.get("house_fias_id") or "").strip()
|
||
if not fias_id:
|
||
continue
|
||
house = str(data.get("house") or "").strip()
|
||
region_kladr = str(data.get("region_kladr_id") or "")
|
||
region_code = region_kladr[:2] if len(region_kladr) >= 2 else ""
|
||
items.append(
|
||
DaDataHouse(
|
||
value=str(suggestion.get("value") or ""),
|
||
fias_id=fias_id,
|
||
house=house,
|
||
house_type=str(data.get("house_type") or ""),
|
||
block=str(data.get("block") or ""),
|
||
block_type=str(data.get("block_type") or ""),
|
||
postal_code=str(data.get("postal_code") or ""),
|
||
street=str(data.get("street") or data.get("street_with_type") or ""),
|
||
city=str(data.get("city") or data.get("settlement") or ""),
|
||
region_code=region_code,
|
||
)
|
||
)
|
||
return items
|
||
|
||
|
||
def _ssl_context() -> ssl.SSLContext:
|
||
context = ssl.create_default_context()
|
||
context.check_hostname = False
|
||
context.verify_mode = ssl.CERT_NONE
|
||
return context
|
||
|
||
|
||
def _suggest_address(token: str, payload: dict) -> list:
|
||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||
request = urllib.request.Request(
|
||
DADATA_SUGGEST_URL,
|
||
data=body,
|
||
headers={
|
||
"Content-Type": "application/json",
|
||
"Accept": "application/json",
|
||
"Authorization": f"Token {token}",
|
||
},
|
||
method="POST",
|
||
)
|
||
try:
|
||
with urllib.request.urlopen(
|
||
request,
|
||
timeout=DADATA_TIMEOUT_SECONDS,
|
||
context=_ssl_context(),
|
||
) as response:
|
||
raw = response.read()
|
||
except Exception as exc:
|
||
logger.warning("DaData suggest/address недоступен: %s", exc)
|
||
return []
|
||
try:
|
||
parsed = json.loads(raw.decode("utf-8"))
|
||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||
logger.warning("DaData suggest/address вернул не JSON")
|
||
return []
|
||
suggestions = parsed.get("suggestions")
|
||
if not isinstance(suggestions, list):
|
||
return []
|
||
return suggestions
|