Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / views / util.py @ 9024ed2e

History | View | Annotate | Download (10.5 kB)

1
# Copyright 2011, 2012, 2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from django.contrib import messages
35
from django.contrib.auth.views import redirect_to_login
36
from django.core.xheaders import populate_xheaders
37
from django.http import HttpResponse
38
from django.shortcuts import redirect
39
from django.template import RequestContext, loader as template_loader
40
from django.utils.translation import ugettext as _
41
from django.views.generic.create_update import apply_extra_context, \
42
    get_model_and_form_class, lookup_object
43

    
44
from synnefo.lib.ordereddict import OrderedDict
45

    
46
from snf_django.lib.db.transaction import commit_on_success_strict
47

    
48
from astakos.im import presentation
49
from astakos.im.util import model_to_dict
50
from astakos.im.models import Resource
51
import astakos.im.messages as astakos_messages
52
import logging
53

    
54
logger = logging.getLogger(__name__)
55

    
56

    
57
class ExceptionHandler(object):
58
    def __init__(self, request):
59
        self.request = request
60

    
61
    def __enter__(self):
62
        pass
63

    
64
    def __exit__(self, exc_type, value, traceback):
65
        if value is not None:  # exception
66
            logger.exception(value)
67
            m = _(astakos_messages.GENERIC_ERROR)
68
            messages.error(self.request, m)
69
            return True  # suppress exception
70

    
71

    
72
def render_response(template, tab=None, status=200, context_instance=None,
73
                    **kwargs):
74
    """
75
    Calls ``django.template.loader.render_to_string`` with an additional
76
    ``tab`` keyword argument and returns an ``django.http.HttpResponse``
77
    with the specified ``status``.
78
    """
79
    if tab is None:
80
        tab = template.partition('_')[0].partition('.html')[0]
81
    kwargs.setdefault('tab', tab)
82
    html = template_loader.render_to_string(
83
        template, kwargs, context_instance=context_instance)
84
    response = HttpResponse(html, status=status)
85
    return response
86

    
87

    
88
def _create_object(request, model=None, template_name=None,
89
                   template_loader=template_loader, extra_context=None,
90
                   post_save_redirect=None, login_required=False,
91
                   context_processors=None, form_class=None, msg=None):
92
    """
93
    Based of django.views.generic.create_update.create_object which displays a
94
    summary page before creating the object.
95
    """
96

    
97
    if extra_context is None:
98
        extra_context = {}
99
    if login_required and not request.user.is_authenticated():
100
        return redirect_to_login(request.path)
101

    
102
    model, form_class = get_model_and_form_class(model, form_class)
103
    extra_context['edit'] = 0
104
    if request.method == 'POST':
105
        form = form_class(request.POST, request.FILES)
106
        if form.is_valid():
107
            verify = request.GET.get('verify')
108
            edit = request.GET.get('edit')
109
            if verify == '1':
110
                extra_context['show_form'] = False
111
                extra_context['form_data'] = form.cleaned_data
112
            elif edit == '1':
113
                extra_context['show_form'] = True
114
            else:
115
                new_object = form.save()
116
                if not msg:
117
                    msg = _(
118
                        "The %(verbose_name)s was created successfully.")
119
                msg = msg % model._meta.__dict__
120
                messages.success(request, msg, fail_silently=True)
121
                return redirect(post_save_redirect, new_object)
122
    else:
123
        form = form_class()
124

    
125
    # Create the template, context, response
126
    if not template_name:
127
        template_name = "%s/%s_form.html" % \
128
            (model._meta.app_label, model._meta.object_name.lower())
129
    t = template_loader.get_template(template_name)
130
    c = RequestContext(request, {
131
        'form': form
132
    }, context_processors)
133
    apply_extra_context(extra_context, c)
134
    return HttpResponse(t.render(c))
135

    
136

    
137
def _update_object(request, model=None, object_id=None, slug=None,
138
                   slug_field='slug', template_name=None,
139
                   template_loader=template_loader, extra_context=None,
140
                   post_save_redirect=None, login_required=False,
141
                   context_processors=None, template_object_name='object',
142
                   form_class=None, msg=None):
143
    """
144
    Based of django.views.generic.create_update.update_object which displays a
145
    summary page before updating the object.
146
    """
147

    
148
    if extra_context is None:
149
        extra_context = {}
150
    if login_required and not request.user.is_authenticated():
151
        return redirect_to_login(request.path)
152

    
153
    model, form_class = get_model_and_form_class(model, form_class)
154
    obj = lookup_object(model, object_id, slug, slug_field)
155

    
156
    if request.method == 'POST':
157
        form = form_class(request.POST, request.FILES, instance=obj)
158
        if form.is_valid():
159
            verify = request.GET.get('verify')
160
            edit = request.GET.get('edit')
161
            if verify == '1':
162
                extra_context['show_form'] = False
163
                extra_context['form_data'] = form.cleaned_data
164
            elif edit == '1':
165
                extra_context['show_form'] = True
166
            else:
167
                obj = form.save()
168
                if not msg:
169
                    msg = _(
170
                        "The %(verbose_name)s was created successfully.")
171
                msg = msg % model._meta.__dict__
172
                messages.success(request, msg, fail_silently=True)
173
                return redirect(post_save_redirect, obj)
174
    else:
175
        form = form_class(instance=obj)
176

    
177
    if not template_name:
178
        template_name = "%s/%s_form.html" % \
179
            (model._meta.app_label, model._meta.object_name.lower())
180
    t = template_loader.get_template(template_name)
181
    c = RequestContext(request, {
182
        'form': form,
183
        template_object_name: obj,
184
    }, context_processors)
185
    apply_extra_context(extra_context, c)
186
    response = HttpResponse(t.render(c))
187
    populate_xheaders(request, response, model,
188
                      getattr(obj, obj._meta.pk.attname))
189
    return response
190

    
191

    
192
def _resources_catalog(for_project=False, for_usage=False):
193
    """
194
    `resource_catalog` contains a list of tuples. Each tuple contains the group
195
    key the resource is assigned to and resources list of dicts that contain
196
    resource information.
197
    `resource_groups` contains information about the groups
198
    """
199
    # presentation data
200
    resources_meta = presentation.RESOURCES
201
    resource_groups = resources_meta.get('groups', {})
202
    resource_catalog = ()
203
    resource_keys = []
204

    
205
    # resources in database
206
    resource_details = map(lambda obj: model_to_dict(obj, exclude=[]),
207
                           Resource.objects.all())
208
    # initialize resource_catalog to contain all group/resource information
209
    for r in resource_details:
210
        if not r.get('group') in resource_groups:
211
            resource_groups[r.get('group')] = {'icon': 'unknown'}
212

    
213
    resource_keys = [r.get('str_repr') for r in resource_details]
214
    resource_catalog = [[g, filter(lambda r: r.get('group', '') == g,
215
                                   resource_details)] for g in resource_groups]
216

    
217
    # order groups, also include unknown groups
218
    groups_order = resources_meta.get('groups_order')
219
    for g in resource_groups.keys():
220
        if not g in groups_order:
221
            groups_order.append(g)
222

    
223
    # order resources, also include unknown resources
224
    resources_order = resources_meta.get('resources_order')
225
    for r in resource_keys:
226
        if not r in resources_order:
227
            resources_order.append(r)
228

    
229
    # sort catalog groups
230
    resource_catalog = sorted(resource_catalog,
231
                              key=lambda g: groups_order.index(g[0]))
232

    
233
    # sort groups
234
    def groupindex(g):
235
        return groups_order.index(g[0])
236
    resource_groups_list = sorted([(k, v) for k, v in resource_groups.items()],
237
                                  key=groupindex)
238
    resource_groups = OrderedDict(resource_groups_list)
239

    
240
    # sort resources
241
    def resourceindex(r):
242
        return resources_order.index(r['str_repr'])
243

    
244
    for index, group in enumerate(resource_catalog):
245
        resource_catalog[index][1] = sorted(resource_catalog[index][1],
246
                                            key=resourceindex)
247
        if len(resource_catalog[index][1]) == 0:
248
            resource_catalog.pop(index)
249
            for gindex, g in enumerate(resource_groups):
250
                if g[0] == group[0]:
251
                    resource_groups.pop(gindex)
252

    
253
    # filter out resources which user cannot request in a project application
254
    exclude = resources_meta.get('exclude_from_usage', [])
255
    for group_index, group_resources in enumerate(list(resource_catalog)):
256
        group, resources = group_resources
257
        for index, resource in list(enumerate(resources)):
258
            if for_project and not resource.get('allow_in_projects'):
259
                resources.remove(resource)
260
            if resource.get('str_repr') in exclude and for_usage:
261
                resources.remove(resource)
262

    
263
    # cleanup empty groups
264
    for group_index, group_resources in enumerate(list(resource_catalog)):
265
        group, resources = group_resources
266
        if len(resources) == 0:
267
            resource_catalog.pop(group_index)
268
            resource_groups.pop(group)
269

    
270
    return resource_catalog, resource_groups