Revision bd1f667b snf-astakos-app/astakos/im/management/commands/resource-import.py

b/snf-astakos-app/astakos/im/management/commands/resource-import.py
38 38
from django.utils import simplejson as json
39 39

  
40 40
from snf_django.lib.db.transaction import commit_on_success_strict
41
from astakos.im.resources import add_resource
41
from astakos.im.register import add_resource, ResourceException
42 42
from astakos.im.models import Service
43 43

  
44 44

  
45 45
class Command(BaseCommand):
46
    help = "Register service resources"
46
    help = "Register resources"
47 47

  
48 48
    option_list = BaseCommand.option_list + (
49 49
        make_option('--json',
......
61 61

  
62 62
        else:
63 63
            with open(json_file) as file_data:
64
                m = ('Input should be a JSON dict containing "service" '
65
                     'and "resource" keys.')
64
                m = 'Input should be a JSON list.'
66 65
                try:
67 66
                    data = json.load(file_data)
68 67
                except json.JSONDecodeError:
69 68
                    raise CommandError(m)
70
                if not isinstance(data, dict):
69
                if not isinstance(data, list):
71 70
                    raise CommandError(m)
72
                else:
73
                    try:
74
                        service = data['service']
75
                        resources = data['resources']
76
                    except KeyError:
77
                        raise CommandError(m)
78

  
79
        self.add_resources(service, resources)
71
        self.add_resources(data)
80 72

  
81 73

  
82 74
    @commit_on_success_strict()
83
    def add_resources(self, service, resources):
84

  
85
        try:
86
            s = Service.objects.get(name=service)
87
        except Service.DoesNotExist:
88
            raise CommandError("Service '%s' is not registered." % (service))
89

  
75
    def add_resources(self, resources):
76
        output = []
90 77
        for resource in resources:
91 78
            if not isinstance(resource, dict):
92 79
                raise CommandError("Malformed resource dict.")
93
            r, exists = add_resource(s, resource)
80
            try:
81
                r, exists = add_resource(resource)
82
            except ResourceException as e:
83
                raise CommandError(e.message)
94 84
            name = r.name
95 85
            if exists:
96 86
                m = "Resource '%s' updated in database.\n" % (name)
97 87
            else:
98 88
                m = ("Resource '%s' created in database with default "
99 89
                     "quota limit 0.\n" % (name))
100
            self.stdout.write(m)
90
            output.append(m)
91

  
92
        for line in output:
93
            self.stdout.write(line)

Also available in: Unified diff