82 lines
3.7 KiB
Python
82 lines
3.7 KiB
Python
from pathlib import Path
|
|
|
|
from django.core.management import call_command
|
|
from django.core.management.base import BaseCommand, CommandError
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = "Импорт адресов, домов и иерархии из архива ГАР/ФИАС без распаковки"
|
|
|
|
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",
|
|
action="append",
|
|
dest="region_codes",
|
|
help="Код региона (можно несколько: --region-code 25 --region-code 27)",
|
|
)
|
|
parser.add_argument(
|
|
"--houses-region-code",
|
|
action="append",
|
|
dest="houses_region_codes",
|
|
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_codes = self._parse_region_codes(options["region_codes"])
|
|
houses_codes = set(self._parse_region_codes(options["houses_region_codes"]))
|
|
extra = {"batch_size": batch_size}
|
|
|
|
if region_codes:
|
|
for region_code in region_codes:
|
|
self._import_region(
|
|
path,
|
|
{**extra, "region_code": region_code},
|
|
import_houses=not houses_codes or region_code in houses_codes,
|
|
)
|
|
elif houses_codes:
|
|
self.stdout.write("Импорт адресных объектов (все регионы)")
|
|
call_command("import_addresses", path, **extra)
|
|
for region_code in sorted(houses_codes):
|
|
self.stdout.write(f"Импорт домов (регион {region_code})")
|
|
call_command("import_houses", path, region_code=region_code, **extra)
|
|
self.stdout.write("Импорт иерархии (все регионы)")
|
|
call_command("import_hierarchy", path, **extra)
|
|
else:
|
|
self._import_region(path, extra)
|
|
self.stdout.write(self.style.SUCCESS(f"Импорт из {path} завершён"))
|
|
|
|
def _import_region(self, path: Path, extra: dict, *, import_houses: bool = True) -> None:
|
|
region = extra.get("region_code")
|
|
title = f"регион {region}" if region else "все регионы"
|
|
self.stdout.write(f"Импорт адресных объектов ({title})")
|
|
call_command("import_addresses", path, **extra)
|
|
if import_houses:
|
|
self.stdout.write(f"Импорт домов ({title})")
|
|
call_command("import_houses", path, **extra)
|
|
self.stdout.write(f"Импорт иерархии ({title})")
|
|
call_command("import_hierarchy", path, **extra)
|
|
|
|
@staticmethod
|
|
def _parse_region_codes(values: list[str] | None) -> list[str]:
|
|
if not values:
|
|
return []
|
|
codes: list[str] = []
|
|
for value in values:
|
|
for part in value.split(","):
|
|
code = part.strip()
|
|
if not code:
|
|
continue
|
|
if not code.isdigit() or len(code) > 2:
|
|
raise CommandError(f"Некорректный код региона: {code}")
|
|
codes.append(f"{int(code):02d}")
|
|
return list(dict.fromkeys(codes))
|