root / snf-astakos-app / astakos / im / views / util.py @ 63c07fdd
History | View | Annotate | Download (11.3 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.exceptions import PermissionDenied |
37 |
from django.core.xheaders import populate_xheaders |
38 |
from django.http import HttpResponse |
39 |
from django.shortcuts import redirect |
40 |
from django.template import RequestContext, loader as template_loader |
41 |
from django.utils.translation import ugettext as _ |
42 |
from django.views.generic.create_update import apply_extra_context, \ |
43 |
get_model_and_form_class, lookup_object |
44 |
|
45 |
from synnefo.lib.ordereddict import OrderedDict |
46 |
|
47 |
from snf_django.lib.db.transaction import commit_on_success_strict |
48 |
|
49 |
from astakos.im import presentation |
50 |
from astakos.im.util import model_to_dict |
51 |
from astakos.im.models import Resource |
52 |
import astakos.im.messages as astakos_messages |
53 |
import logging |
54 |
|
55 |
logger = logging.getLogger(__name__) |
56 |
|
57 |
|
58 |
class ExceptionHandler(object): |
59 |
def __init__(self, request): |
60 |
self.request = request
|
61 |
|
62 |
def __enter__(self): |
63 |
pass
|
64 |
|
65 |
def __exit__(self, exc_type, value, traceback): |
66 |
if value is not None: # exception |
67 |
logger.exception(value) |
68 |
m = _(astakos_messages.GENERIC_ERROR) |
69 |
messages.error(self.request, m)
|
70 |
return True # suppress exception |
71 |
|
72 |
|
73 |
def render_response(template, tab=None, status=200, context_instance=None, **kwargs): |
74 |
"""
|
75 |
Calls ``django.template.loader.render_to_string`` with an additional ``tab``
|
76 |
keyword argument and returns an ``django.http.HttpResponse`` with the
|
77 |
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 |
@commit_on_success_strict()
|
88 |
def _create_object(request, model=None, template_name=None, |
89 |
template_loader=template_loader, extra_context=None, post_save_redirect=None, |
90 |
login_required=False, context_processors=None, form_class=None, |
91 |
msg=None, summary_template_name=None): |
92 |
"""
|
93 |
Based of django.views.generic.create_update.create_object which displays a
|
94 |
summary page before creating the object.
|
95 |
"""
|
96 |
response = None
|
97 |
|
98 |
if extra_context is None: extra_context = {} |
99 |
if login_required and not request.user.is_authenticated(): |
100 |
return redirect_to_login(request.path)
|
101 |
try:
|
102 |
|
103 |
model, form_class = get_model_and_form_class(model, form_class) |
104 |
extra_context['edit'] = 0 |
105 |
if request.method == 'POST': |
106 |
form = form_class(request.POST, request.FILES) |
107 |
if form.is_valid():
|
108 |
verify = request.GET.get('verify')
|
109 |
edit = request.GET.get('edit')
|
110 |
if verify == '1': |
111 |
extra_context['show_form'] = False |
112 |
extra_context['form_data'] = form.cleaned_data
|
113 |
template_name = summary_template_name |
114 |
elif edit == '1': |
115 |
extra_context['show_form'] = True |
116 |
else:
|
117 |
new_object = form.save() |
118 |
if not msg: |
119 |
msg = _("The %(verbose_name)s was created successfully.")
|
120 |
msg = msg % model._meta.__dict__ |
121 |
messages.success(request, msg, fail_silently=True)
|
122 |
response = redirect(post_save_redirect, new_object) |
123 |
else:
|
124 |
form = form_class() |
125 |
except (IOError, PermissionDenied), e: |
126 |
messages.error(request, e) |
127 |
return None |
128 |
else:
|
129 |
if response == None: |
130 |
# Create the template, context, response
|
131 |
if not template_name: |
132 |
template_name = "%s/%s_form.html" %\
|
133 |
(model._meta.app_label, model._meta.object_name.lower()) |
134 |
t = template_loader.get_template(template_name) |
135 |
c = RequestContext(request, { |
136 |
'form': form
|
137 |
}, context_processors) |
138 |
apply_extra_context(extra_context, c) |
139 |
response = HttpResponse(t.render(c)) |
140 |
return response
|
141 |
|
142 |
@commit_on_success_strict()
|
143 |
def _update_object(request, model=None, object_id=None, slug=None, |
144 |
slug_field='slug', template_name=None, template_loader=template_loader, |
145 |
extra_context=None, post_save_redirect=None, login_required=False, |
146 |
context_processors=None, template_object_name='object', |
147 |
form_class=None, msg=None, summary_template_name=None): |
148 |
"""
|
149 |
Based of django.views.generic.create_update.update_object which displays a
|
150 |
summary page before updating the object.
|
151 |
"""
|
152 |
response = None
|
153 |
|
154 |
if extra_context is None: extra_context = {} |
155 |
if login_required and not request.user.is_authenticated(): |
156 |
return redirect_to_login(request.path)
|
157 |
|
158 |
try:
|
159 |
model, form_class = get_model_and_form_class(model, form_class) |
160 |
obj = lookup_object(model, object_id, slug, slug_field) |
161 |
|
162 |
if request.method == 'POST': |
163 |
form = form_class(request.POST, request.FILES, instance=obj) |
164 |
if form.is_valid():
|
165 |
verify = request.GET.get('verify')
|
166 |
edit = request.GET.get('edit')
|
167 |
if verify == '1': |
168 |
extra_context['show_form'] = False |
169 |
extra_context['form_data'] = form.cleaned_data
|
170 |
template_name = summary_template_name |
171 |
elif edit == '1': |
172 |
extra_context['show_form'] = True |
173 |
else:
|
174 |
obj = form.save() |
175 |
if not msg: |
176 |
msg = _("The %(verbose_name)s was created successfully.")
|
177 |
msg = msg % model._meta.__dict__ |
178 |
messages.success(request, msg, fail_silently=True)
|
179 |
response = redirect(post_save_redirect, obj) |
180 |
else:
|
181 |
form = form_class(instance=obj) |
182 |
except (IOError, PermissionDenied), e: |
183 |
messages.error(request, e) |
184 |
return None |
185 |
else:
|
186 |
if response == None: |
187 |
if not template_name: |
188 |
template_name = "%s/%s_form.html" %\
|
189 |
(model._meta.app_label, model._meta.object_name.lower()) |
190 |
t = template_loader.get_template(template_name) |
191 |
c = RequestContext(request, { |
192 |
'form': form,
|
193 |
template_object_name: obj, |
194 |
}, context_processors) |
195 |
apply_extra_context(extra_context, c) |
196 |
response = HttpResponse(t.render(c)) |
197 |
populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.attname))
|
198 |
return response
|
199 |
|
200 |
def _resources_catalog(for_project=False, for_usage=False): |
201 |
"""
|
202 |
`resource_catalog` contains a list of tuples. Each tuple contains the group
|
203 |
key the resource is assigned to and resources list of dicts that contain
|
204 |
resource information.
|
205 |
`resource_groups` contains information about the groups
|
206 |
"""
|
207 |
# presentation data
|
208 |
resources_meta = presentation.RESOURCES |
209 |
resource_groups = resources_meta.get('groups', {})
|
210 |
resource_catalog = () |
211 |
resource_keys = [] |
212 |
|
213 |
# resources in database
|
214 |
resource_details = map(lambda obj: model_to_dict(obj, exclude=[]), |
215 |
Resource.objects.all()) |
216 |
# initialize resource_catalog to contain all group/resource information
|
217 |
for r in resource_details: |
218 |
if not r.get('group') in resource_groups: |
219 |
resource_groups[r.get('group')] = {'icon': 'unknown'} |
220 |
|
221 |
resource_keys = [r.get('str_repr') for r in resource_details] |
222 |
resource_catalog = [[g, filter(lambda r: r.get('group', '') == g, |
223 |
resource_details)] for g in resource_groups] |
224 |
|
225 |
# order groups, also include unknown groups
|
226 |
groups_order = resources_meta.get('groups_order')
|
227 |
for g in resource_groups.keys(): |
228 |
if not g in groups_order: |
229 |
groups_order.append(g) |
230 |
|
231 |
# order resources, also include unknown resources
|
232 |
resources_order = resources_meta.get('resources_order')
|
233 |
for r in resource_keys: |
234 |
if not r in resources_order: |
235 |
resources_order.append(r) |
236 |
|
237 |
# sort catalog groups
|
238 |
resource_catalog = sorted(resource_catalog,
|
239 |
key=lambda g: groups_order.index(g[0])) |
240 |
|
241 |
# sort groups
|
242 |
def groupindex(g): |
243 |
return groups_order.index(g[0]) |
244 |
resource_groups_list = sorted([(k, v) for k, v in resource_groups.items()], |
245 |
key=groupindex) |
246 |
resource_groups = OrderedDict(resource_groups_list) |
247 |
|
248 |
# sort resources
|
249 |
def resourceindex(r): |
250 |
return resources_order.index(r['str_repr']) |
251 |
|
252 |
for index, group in enumerate(resource_catalog): |
253 |
resource_catalog[index][1] = sorted(resource_catalog[index][1], |
254 |
key=resourceindex) |
255 |
if len(resource_catalog[index][1]) == 0: |
256 |
resource_catalog.pop(index) |
257 |
for gindex, g in enumerate(resource_groups): |
258 |
if g[0] == group[0]: |
259 |
resource_groups.pop(gindex) |
260 |
|
261 |
# filter out resources which user cannot request in a project application
|
262 |
exclude = resources_meta.get('exclude_from_usage', [])
|
263 |
for group_index, group_resources in enumerate(list(resource_catalog)): |
264 |
group, resources = group_resources |
265 |
for index, resource in list(enumerate(resources)): |
266 |
if for_project and not resource.get('allow_in_projects'): |
267 |
resources.remove(resource) |
268 |
if resource.get('str_repr') in exclude and for_usage: |
269 |
resources.remove(resource) |
270 |
|
271 |
# cleanup empty groups
|
272 |
for group_index, group_resources in enumerate(list(resource_catalog)): |
273 |
group, resources = group_resources |
274 |
if len(resources) == 0: |
275 |
resource_catalog.pop(group_index) |
276 |
resource_groups.pop(group) |
277 |
|
278 |
|
279 |
return resource_catalog, resource_groups
|