import os import yaml from django.conf import settings from django.core.management.base import BaseCommand, CommandError from suitablephones.models import Bluetooth, Camera, Device import logging def set_camera(args): cam = Camera.objects.filter(**args) if not cam.exists(): cam = Camera() for subkey, subvalue in args.items(): if subkey == 'info': mp = subvalue.split(' ')[0] setattr(cam, 'megapixel', mp) info = ' '.join(map(str, subvalue.split(' ')[2:])) setattr(cam, subkey, info) setattr(cam, subkey, subvalue) cam.save() else: cam = cam.get() return cam class Command(BaseCommand): help = 'Aiuto' #def add_arguments(self, parser): # parser.add_argument('poll_ids', nargs='+', type=int def handle(self, *args, **options): Device.objects.all().delete() Bluetooth.objects.all().delete() Camera.objects.all().delete() devicesdir = settings.LINEAGEWIKI + "/_data/devices/" # import pdb; pdb.set_trace() for filename in os.listdir(devicesdir): dev = Device() cameras = [] bluetooth = {} peripherals = [] with open(os.path.join(devicesdir, filename), "r") as stream: try: data = yaml.safe_load(stream) print(data['codename']) for key, value in data.items(): # if key == "architecture": # if type(value) == dict(): # setattr(dev, key, value) # else: #type(value) == str(): # setattr(dev, key, dict({ 'cpu' : value })) #match caso: # case dict(): # print('dict') if key == "bluetooth": if not 'profiles' in value.keys(): value['profiles'] = None # get() returned more than one Bluetooth -- it returned 2! bt = Bluetooth.objects.filter(**value) # __exact? https://docs.djangoproject.com/en/4.1/ref/models/querysets/#exact if not bt.exists(): bt = Bluetooth() for subkey, subvalue in value.items(): if not hasattr(value, 'profiles'): setattr(bt, 'profiles', None) setattr(bt, subkey, subvalue) bt.save() else: bt = bt.get(spec=value['spec'], profiles=value['profiles']) bluetooth = bt elif key == "cameras": for c in value: cam = set_camera(c) cameras.append(cam) elif key == "peripherals": if str(value) == "None": value = None elif key == "storage": if str(value) == "None": value = None else: setattr(dev, key, value) except yaml.YAMLError as exc: print(exc) stream.close() dev.save() dev.bluetooth = bluetooth for cam in cameras: dev.cameras.add(cam) dev.save()