from datetime import date from pathlib import Path from uuid import UUID from xml.etree import ElementTree from django.core.management.base import BaseCommand, CommandError from address.management.commands.import_addresses import infer_region_code from address.models import House REQUIRED_ATTRIBUTES = ( "OBJECTID", "OBJECTGUID", "UPDATEDATE", "ISACTUAL", "ISACTIVE", ) class Command(BaseCommand): help = "Импорт домов из XML HOUSES выгрузки ГАР/ФИАС" 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 not path.is_file(): raise CommandError(f"Файл не найден: {path}") if batch_size < 1: raise CommandError("Размер пакета должен быть больше нуля") region_code = options["region_code"] or infer_region_code(path) if not region_code or len(region_code) > 2 or not region_code.isdigit(): raise CommandError( "Не удалось определить код региона. Передайте его через --region-code" ) region_code = region_code.zfill(2) objects = [] imported = 0 try: for _, element in ElementTree.iterparse(path, events=("end",)): if element.tag.rsplit("}", 1)[-1] != "HOUSE": continue objects.append(self._make_house(element.attrib, region_code)) element.clear() if len(objects) >= batch_size: self._save(objects, batch_size) imported += len(objects) objects.clear() except (ElementTree.ParseError, OSError) as error: raise CommandError(f"Не удалось прочитать XML {path}: {error}") from error if objects: self._save(objects, batch_size) imported += len(objects) self.stdout.write(self.style.SUCCESS(f"Импортировано домов: {imported}")) @staticmethod def _make_house(attributes: dict[str, str], region_code: str) -> House: missing = [name for name in REQUIRED_ATTRIBUTES if not attributes.get(name)] if missing: record_id = attributes.get("ID", "неизвестен") raise CommandError( f"У записи дома {record_id} отсутствуют атрибуты: {', '.join(missing)}" ) try: return House( object_id=int(attributes["OBJECTID"]), fias_id=UUID(attributes["OBJECTGUID"]), region_code=region_code, house_number=attributes.get("HOUSENUM", "").strip(), house_type=Command._optional_type(attributes, "HOUSETYPE"), additional_number_1=attributes.get("ADDNUM1", "").strip(), additional_type_1=Command._optional_type(attributes, "ADDTYPE1"), additional_number_2=attributes.get("ADDNUM2", "").strip(), additional_type_2=Command._optional_type(attributes, "ADDTYPE2"), source_updated_at=date.fromisoformat(attributes["UPDATEDATE"]), is_actual=attributes["ISACTUAL"] == "1", is_active=attributes["ISACTIVE"] == "1", ) except (TypeError, ValueError) as error: record_id = attributes.get("ID", "неизвестен") raise CommandError(f"Некорректные данные дома {record_id}: {error}") from error @staticmethod def _optional_type(attributes: dict[str, str], name: str) -> int | None: value = attributes.get(name) if not value: return None type_id = int(value) if type_id not in House.Type.values: raise ValueError(f"неизвестный тип дома {name}={type_id}") return type_id @staticmethod def _save(objects: list[House], batch_size: int) -> None: House.objects.bulk_create( objects, batch_size=batch_size, update_conflicts=True, unique_fields=("fias_id",), update_fields=( "object_id", "region_code", "house_number", "house_type", "additional_number_1", "additional_type_1", "additional_number_2", "additional_type_2", "source_updated_at", "is_actual", "is_active", ), )