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

154 lines
5.7 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 uuid import UUID
from xml.etree import ElementTree
from zipfile import BadZipFile
from django.core.management.base import BaseCommand, CommandError
from address.fias_archive import KIND_HOUSES, iter_fias_xml, iterparse_xml
from address.models import House
IMPORT_HOUSE_TYPES = frozenset(
{
House.Type.POSSESSION,
House.Type.HOUSE,
House.Type.HOUSEHOLD,
House.Type.LITERA,
House.Type.BLOCK,
}
)
REQUIRED_ATTRIBUTES = (
"OBJECTID",
"OBJECTGUID",
"ISACTUAL",
"ISACTIVE",
)
class Command(BaseCommand):
help = "Импорт домов из XML или ZIP 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 batch_size < 1:
raise CommandError("Размер пакета должен быть больше нуля")
imported = 0
try:
for label, region_code, source in iter_fias_xml(
path, KIND_HOUSES, options["region_code"]
):
count = self._import_source(source, int(region_code), batch_size)
imported += 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"Импортировано домов: {imported}"))
def _import_source(self, source, region_code: int, batch_size: int) -> int:
objects = []
imported = 0
for _, element in iterparse_xml(source):
if element.tag.rsplit("}", 1)[-1] != "HOUSE":
continue
if (
element.attrib.get("ISACTUAL") != "1"
or element.attrib.get("ISACTIVE") != "1"
):
element.clear()
continue
raw_type = element.attrib.get("HOUSETYPE")
if raw_type:
try:
house_type = int(raw_type)
except ValueError:
house_type = None
else:
if (
house_type in House.Type.values
and house_type not in IMPORT_HOUSE_TYPES
):
element.clear()
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()
if objects:
self._save(objects, batch_size)
imported += len(objects)
return imported
@staticmethod
def _make_house(attributes: dict[str, str], region_code: int) -> 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=Command._optional_text(attributes.get("HOUSENUM")),
house_type=Command._optional_type(attributes, "HOUSETYPE"),
additional_number_1=Command._optional_text(attributes.get("ADDNUM1")),
additional_type_1=Command._optional_type(attributes, "ADDTYPE1"),
additional_number_2=Command._optional_text(attributes.get("ADDNUM2")),
additional_type_2=Command._optional_type(attributes, "ADDTYPE2"),
)
except (TypeError, ValueError) as error:
record_id = attributes.get("ID", "неизвестен")
raise CommandError(f"Некорректные данные дома {record_id}: {error}") from error
@staticmethod
def _optional_text(value: str | None) -> str | None:
text = (value or "").strip()
return text or None
@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:
objects = list({obj.fias_id: obj for obj in objects}.values())
objects = list({obj.object_id: obj for obj in objects}.values())
House.objects.bulk_create(
objects,
batch_size=batch_size,
update_conflicts=True,
unique_fields=("object_id",),
update_fields=(
"fias_id",
"region_code",
"house_number",
"house_type",
"additional_number_1",
"additional_type_1",
"additional_number_2",
"additional_type_2",
),
)