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

116 lines
4.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 uuid import UUID
from xml.etree import ElementTree
from django.core.management.base import BaseCommand, CommandError
from address.models import AddressObject
REQUIRED_ATTRIBUTES = (
"OBJECTID",
"OBJECTGUID",
"NAME",
"TYPENAME",
"LEVEL",
"ISACTUAL",
"ISACTIVE",
)
def infer_region_code(path: Path) -> str | None:
"""Infer the FIAS region code from a directory in the XML path."""
return next(
(part for part in reversed(path.parts[:-1]) if len(part) == 2 and part.isdigit()),
None,
)
class Command(BaseCommand):
help = "Импорт адресных объектов из XML выгрузки ГАР/ФИАС"
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="Код региона ФИАС (по умолчанию определяется по каталогу файла, например 25)",
)
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] != "OBJECT":
continue
if element.attrib.get("ISACTUAL") != "1":
element.clear()
continue
objects.append(self._make_object(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_object(attributes: dict[str, str], region_code: str) -> AddressObject:
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 AddressObject(
fias_id=UUID(attributes["OBJECTGUID"]),
object_id=int(attributes["OBJECTID"]),
name=attributes["NAME"].strip(),
type_name=attributes["TYPENAME"].strip(),
level=int(attributes["LEVEL"]),
region_code=region_code,
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 _save(objects: list[AddressObject], batch_size: int) -> None:
objects = list({obj.fias_id: obj for obj in objects}.values())
AddressObject.objects.bulk_create(
objects,
batch_size=batch_size,
update_conflicts=True,
unique_fields=("fias_id",),
update_fields=(
"object_id",
"name",
"type_name",
"level",
"region_code",
"is_active",
),
)