Misc cleanup

This commit is contained in:
Jeremy Stretch 2023-08-07 16:19:00 -04:00
parent 22ecc96de2
commit b699c7bd98

View File

@ -1,16 +1,11 @@
import json
import os
from json import dumps as json_dumps
from json import loads as json_loads
from django.conf import settings
from django.core.management.base import BaseCommand
from jinja2 import FileSystemLoader, Environment
from dcim.choices import (
DeviceAirflowChoices, SubdeviceRoleChoices, ConsolePortTypeChoices, PowerPortTypeChoices,
PowerOutletTypeChoices, PowerOutletFeedLegChoices, InterfaceTypeChoices, InterfacePoEModeChoices,
InterfacePoETypeChoices, PortTypeChoices, WeightUnitChoices
)
from dcim.choices import *
TEMPLATE_FILENAME = 'generated_schema.json'
OUTPUT_FILENAME = 'contrib/generated_schema.json'
@ -20,7 +15,7 @@ CHOICES_MAP = {
'weight_unit_choices': WeightUnitChoices,
'subdevice_role_choices': SubdeviceRoleChoices,
'console_port_type_choices': ConsolePortTypeChoices,
'console_server_port_type_choices': ConsolePortTypeChoices, # Reusing ConsolePortTypeChoices
'console_server_port_type_choices': ConsolePortTypeChoices,
'power_port_type_choices': PowerPortTypeChoices,
'power_outlet_type_choices': PowerOutletTypeChoices,
'power_outlet_feedleg_choices': PowerOutletFeedLegChoices,
@ -28,12 +23,12 @@ CHOICES_MAP = {
'interface_poe_mode_choices': InterfacePoEModeChoices,
'interface_poe_type_choices': InterfacePoETypeChoices,
'front_port_type_choices': PortTypeChoices,
'rear_port_type_choices': PortTypeChoices, # Reusing PortTypeChoices
'rear_port_type_choices': PortTypeChoices,
}
class Command(BaseCommand):
help = "Generate the NetBox validation schemas."
help = "Generate JSON schema for the NetBox device type library"
def add_arguments(self, parser):
parser.add_argument(
@ -43,11 +38,14 @@ class Command(BaseCommand):
)
def handle(self, *args, **kwargs):
# Initialize template
template_loader = FileSystemLoader(searchpath=f'{settings.TEMPLATES_DIR}/extras/')
template_env = Environment(loader=template_loader)
template = template_env.get_template(TEMPLATE_FILENAME)
# Render template
context = {
key: json_dumps(choices.values())
key: json.dumps(choices.values())
for key, choices in CHOICES_MAP.items()
}
rendered = template.render(**context)
@ -56,7 +54,7 @@ class Command(BaseCommand):
# $root/contrib/generated_schema.json
filename = os.path.join(os.path.split(settings.BASE_DIR)[0], OUTPUT_FILENAME)
with open(filename, mode='w', encoding='UTF-8') as f:
f.write(json_dumps(json_loads(rendered), indent=4))
f.write(json.dumps(json.loads(rendered), indent=4))
f.write('\n')
f.close()
self.stdout.write(self.style.SUCCESS(f"Schema written to {filename}."))