address-service/address/management/commands/import_hierarchy.py

247 lines
9.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from pathlib import Path
from xml.etree import ElementTree
from zipfile import BadZipFile
from django.core.management.base import BaseCommand, CommandError
from address.cache import invalidate_search_cache
from address.fias_archive import (
KIND_HIERARCHY,
KIND_MUN_HIERARCHY,
is_zip_archive,
iter_fias_xml,
iterparse_xml,
)
from address.models import AddressObject, House
HOUSE_PARENT_LEVELS = (
AddressObject.Level.STREET,
AddressObject.Level.PLANNING,
)
SKIP_HOUSE_PARENT_LEVELS = frozenset(
{
AddressObject.Level.REGION,
AddressObject.Level.DISTRICT,
AddressObject.Level.MUNICIPAL_DISTRICT,
AddressObject.Level.MUNICIPAL_SETTLEMENT,
AddressObject.Level.CITY,
AddressObject.Level.SETTLEMENT,
}
)
SKIP_HOUSE = object()
ObjectInfo = tuple[int, int, str]
def parse_path(path: str, object_id: int) -> list[int]:
ancestor_ids = [int(part) for part in path.split(".") if part]
if ancestor_ids and ancestor_ids[-1] == object_id:
ancestor_ids.pop()
ancestor_ids.reverse()
return ancestor_ids
def item_ancestor_ids(attributes: dict[str, str], object_id: int) -> list[int]:
ancestor_ids = parse_path(attributes.get("PATH", ""), object_id)
if ancestor_ids:
return ancestor_ids
try:
parent_object_id = int(attributes.get("PARENTOBJID") or 0)
except (TypeError, ValueError):
return []
return [parent_object_id] if parent_object_id else []
def resolve_parent_pk(
object_id: int,
ancestor_ids: list[int],
objects: dict[int, ObjectInfo],
) -> int | None:
child = objects.get(object_id)
if child is None:
return None
child_pk, _child_level, _type_name = child
for ancestor_id in ancestor_ids:
ancestor = objects.get(ancestor_id)
if ancestor is None:
continue
parent_pk, _parent_level, _type_name = ancestor
if parent_pk == child_pk:
continue
return parent_pk
return None
def resolve_house_parent_pk(
ancestor_ids: list[int],
objects: dict[int, ObjectInfo],
) -> int | object | None:
if ancestor_ids and ancestor_ids[0] not in objects:
return SKIP_HOUSE
for ancestor_id in ancestor_ids:
ancestor = objects.get(ancestor_id)
if ancestor is None:
continue
parent_pk, parent_level, _type_name = ancestor
if parent_level in SKIP_HOUSE_PARENT_LEVELS:
return SKIP_HOUSE
if parent_level in HOUSE_PARENT_LEVELS:
return parent_pk
return None
class Command(BaseCommand):
help = "Заполнить parent из XML или ZIP AS_ADM_HIERARCHY и AS_MUN_HIERARCHY"
def add_arguments(self, parser):
parser.add_argument("file", type=Path)
parser.add_argument("--batch-size", type=int, default=2000)
parser.add_argument(
"--region-code",
help="Код региона ФИАС (по умолчанию определяется по каталогу файла)",
)
def handle(self, *args, **options):
path = options["file"]
batch_size = options["batch_size"]
if batch_size < 1:
raise CommandError("Размер пакета должен быть больше нуля")
updated_addresses = 0
updated_houses = 0
skipped_houses = 0
sources = [
(KIND_HIERARCHY, False, False),
]
if is_zip_archive(path):
sources.append((KIND_MUN_HIERARCHY, True, True))
try:
for kind, optional, empty_only in sources:
for label, region_code, source in iter_fias_xml(
path,
kind,
options["region_code"],
require_region=False,
optional=optional,
):
addresses, houses, skipped = self._import_source(
source,
region_code,
batch_size,
empty_only=empty_only,
)
updated_addresses += addresses
updated_houses += houses
skipped_houses += skipped
self.stdout.write(
f"{label}: адресов {addresses}, домов {houses}, пропущено {skipped}"
)
except (ElementTree.ParseError, OSError, BadZipFile) as error:
raise CommandError(f"Не удалось прочитать XML {path}: {error}") from error
self.stdout.write(
self.style.SUCCESS(
f"Обновлено родителей: {updated_addresses} адресных объектов, "
f"{updated_houses} домов, пропущено домов: {skipped_houses}"
)
)
invalidate_search_cache()
def _import_source(
self,
source,
region_code: str | None,
batch_size: int,
*,
empty_only: bool = False,
) -> tuple[int, int, int]:
queryset = AddressObject.objects.filter(object_id__isnull=False)
house_queryset = House.objects.all()
if region_code:
code = int(region_code)
queryset = queryset.filter(region_code=code)
house_queryset = house_queryset.filter(region_code=code)
records = {
object_id: (pk, level, parent_id)
for object_id, pk, level, parent_id in queryset.values_list(
"object_id", "id", "level", "parent_id"
)
}
objects = {
object_id: (pk, level, type_name)
for object_id, pk, level, type_name in queryset.values_list(
"object_id", "id", "level", "type_name"
)
}
houses = set() if empty_only else set(house_queryset.values_list("object_id", flat=True))
address_updates: dict[int, AddressObject] = {}
house_updates: dict[int, House] = {}
fallback_addresses: dict[int, AddressObject] = {}
fallback_houses: dict[int, House] = {}
house_deletes: set[int] = set()
for _, element in iterparse_xml(source):
if element.tag.rsplit("}", 1)[-1] != "ITEM":
continue
attributes = element.attrib
element.clear()
is_active = attributes.get("ISACTIVE") == "1"
try:
object_id = int(attributes["OBJECTID"])
except (KeyError, TypeError, ValueError):
continue
ancestor_ids = item_ancestor_ids(attributes, object_id)
if object_id in records:
pk, _level, parent_id = records[object_id]
if empty_only and parent_id is not None:
continue
parent_pk = resolve_parent_pk(object_id, ancestor_ids, objects)
update = AddressObject(pk=pk, parent_id=parent_pk)
if is_active:
address_updates[pk] = update
fallback_addresses.pop(pk, None)
elif pk not in address_updates:
fallback_addresses[pk] = update
elif object_id in houses:
parent_pk = resolve_house_parent_pk(ancestor_ids, objects)
if parent_pk is SKIP_HOUSE:
if is_active:
house_deletes.add(object_id)
house_updates.pop(object_id, None)
fallback_houses.pop(object_id, None)
elif object_id not in house_updates:
house_deletes.add(object_id)
continue
update = House(pk=object_id, parent_id=parent_pk)
if is_active:
house_updates[object_id] = update
fallback_houses.pop(object_id, None)
house_deletes.discard(object_id)
elif object_id not in house_updates:
fallback_houses[object_id] = update
address_updates.update(
{pk: obj for pk, obj in fallback_addresses.items() if pk not in address_updates}
)
house_updates.update(
{oid: obj for oid, obj in fallback_houses.items() if oid not in house_updates}
)
house_updates = {
oid: obj for oid, obj in house_updates.items() if oid not in house_deletes
}
updated_addresses = self._bulk_update(
address_updates, AddressObject, ["parent"], batch_size
)
updated_houses = self._bulk_update(house_updates, House, ["parent"], batch_size)
skipped_houses = 0
if house_deletes:
skipped_houses, _ = House.objects.filter(object_id__in=house_deletes).delete()
return updated_addresses, updated_houses, skipped_houses
@staticmethod
def _bulk_update(updates: dict, model, fields: list[str], batch_size: int) -> int:
batch = list(updates.values())
for start in range(0, len(batch), batch_size):
model.objects.bulk_update(batch[start : start + batch_size], fields)
return len(batch)