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

83 lines
3.3 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_ADDR_PARAMS, iter_fias_xml, iterparse_xml
from address.models import AddressObject
KLADR_TYPE_ID = "10"
KLADR_CODE_LENGTHS = frozenset({13, 17})
class Command(BaseCommand):
help = "Заполнить код КЛАДР адресных объектов из XML PARAMS ГАР/ФИАС (TYPEID=10)"
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 = 0
try:
for label, region_code, source in iter_fias_xml(
path,
KIND_ADDR_PARAMS,
options["region_code"],
require_region=False,
):
count = self._import_source(source, region_code, batch_size)
updated += count
self.stdout.write(f"{label}: {count}")
except (ElementTree.ParseError, OSError, BadZipFile) as error:
raise CommandError(f"Не удалось прочитать XML {path}: {error}") from error
self.stdout.write(self.style.SUCCESS(f"Обновлено кодов КЛАДР: {updated}"))
invalidate_search_cache()
def _import_source(self, source, region_code: str | None, batch_size: int) -> int:
objects = AddressObject.objects.filter(object_id__isnull=False)
if region_code:
objects = objects.filter(region_code=int(region_code))
object_ids = dict(objects.values_list("object_id", "id"))
codes: dict[int, str] = {}
for _, element in iterparse_xml(source):
if element.tag.rsplit("}", 1)[-1] != "PARAM":
continue
attributes = element.attrib
element.clear()
if attributes.get("TYPEID") != KLADR_TYPE_ID:
continue
if attributes.get("CHANGEIDEND") != "0":
continue
value = attributes.get("VALUE", "").strip()
if len(value) not in KLADR_CODE_LENGTHS or not value.isdigit():
continue
try:
object_id = int(attributes["OBJECTID"])
except (KeyError, TypeError, ValueError):
continue
pk = object_ids.get(object_id)
if pk is not None:
codes[pk] = value
return self._bulk_update(codes, batch_size)
@staticmethod
def _bulk_update(codes: dict[int, str], batch_size: int) -> int:
batch = [AddressObject(pk=pk, kladr_id=code) for pk, code in codes.items()]
for start in range(0, len(batch), batch_size):
AddressObject.objects.bulk_update(batch[start : start + batch_size], ["kladr_id"])
return len(batch)