# -*- coding: UTF-8 -*-
import json
import logging
import os
import pprint
import re
import shutil
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from iconolab.management.commands.importimages import BaseImportImagesCommand
from iconolab.models import (Collection, Folder, Image, ImageStats, Item,
ItemMetadata, MetaCategory)
if settings.IMPORT_LOGGER_NAME and settings.LOGGING['loggers'].get(settings.IMPORT_LOGGER_NAME, ''):
logger = logging.getLogger(settings.IMPORT_LOGGER_NAME)
else:
logger = logging.getLogger(__name__)
class Command(BaseImportImagesCommand):
help = 'import metacategories files from a directory'
def add_arguments(self, parser):
parser.add_argument('source_dir')
parser.add_argument(
'--encoding',
dest='encoding',
default='utf-8',
help='JSON file encoding'
)
parser.add_argument(
'--collection-id',
dest='collection_id',
default=False,
help='insert extracted data into the specified collection instead of trying to load a collection fixture',
)
parser.add_argument(
'--metacategories-json',
dest='metacategories_json',
default=False,
help='add metacategories to the collection from a json file (json must be a list of object with "label" and "triggers_notifications" fields)',
)
def handle(self, *args, **options):
print('# Logging with logger '+logger.name)
logger.debug('# Initializing command with args: %r', options)
self.source_dir = options.get('source_dir')
if options.get('collection_id'):
print('## Finding collection with id ' +
options.get('collection_id'))
try:
collection = Collection.objects.get(
pk=options.get('collection_id'))
except Collection.DoesNotExist:
raise ValueError('!!! Collection with primary key ' +
options.get('collection_id')+' was not found, aborting !!!')
else:
raise ValueError(
'!!! No collection fixture or collection id, aborting because we can\'t properly generate data. !!!')
if options.get('metacategories_json'):
print('## Finding metacategories fixture json data in '+self.source_dir)
metacategories_json_path = os.path.join(
self.source_dir, options.get('metacategories_json'))
if not os.path.isfile(metacategories_json_path):
print('### No '+options.get('metacategories_json')+
'.json file was found in the source directory')
raise ValueError(
'!!! Fixture file '+metacategories_json_path+' was not found !!!')
with open(metacategories_json_path) as metacategories_json_file:
metacategories_data = json.loads(
metacategories_json_file.read())
for metacategory in metacategories_data:
if metacategory.get('label', None) is None:
raise ValueError(
'!!! Metacategory without label !!!')
if options.get('metacategories_json'):
for metacategory in metacategories_data:
MetaCategory.objects.create(
collection=collection,
label=metacategory.get('label'),
triggers_notifications=metacategory.get(
'triggers_notifications', 0)
)