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

79 lines
3.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.fias_archive import KIND_HOUSE_PARAMS, iter_fias_xml, iterparse_xml
from address.models import House
POSTAL_TYPE_ID = "5"
class Command(BaseCommand):
help = "Заполнить почтовый индекс домов из XML PARAMS ГАР/ФИАС (TYPEID=5)"
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_HOUSE_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} домов"))
def _import_source(self, source, region_code: str | None, batch_size: int) -> int:
houses = House.objects.all()
if region_code:
houses = houses.filter(region_code=int(region_code))
known_ids = set(houses.values_list("pk", flat=True))
house_codes: dict[int, int] = {}
for _, element in iterparse_xml(source):
if element.tag.rsplit("}", 1)[-1] != "PARAM":
continue
attributes = element.attrib
element.clear()
if attributes.get("TYPEID") != POSTAL_TYPE_ID:
continue
if attributes.get("CHANGEIDEND") != "0":
continue
value = attributes.get("VALUE", "").strip()
if len(value) != 6 or not value.isdigit():
continue
try:
object_id = int(attributes["OBJECTID"])
except (KeyError, TypeError, ValueError):
continue
if object_id in known_ids:
house_codes[object_id] = int(value)
return self._bulk_update(house_codes, batch_size)
@staticmethod
def _bulk_update(codes: dict[int, int], batch_size: int) -> int:
batch = [House(pk=pk, postal_code=code) for pk, code in codes.items()]
for start in range(0, len(batch), batch_size):
House.objects.bulk_update(batch[start : start + batch_size], ["postal_code"])
return len(batch)