Parent: [c9d94b] (diff)

Child: [c22082] (diff)

Download this file

views.py    245 lines (216 with data), 13.1 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404, render_to_response, redirect
from django.template import RequestContext
from django.utils import simplejson, timezone
from django.views.generic import ListView
from xml.dom import minidom
from forms import AnalysisForm, UploadFileForm, ImportChoice, MyModelForm
from analysis.models import Analysis, Configuration, Instance, UploadedFile, Answer, Methodology, MethodologyVersion, Question, Page
#from methodology.models import Methodology, MethodologyVersion, Question, Page
from OSSEval.utils import xmlMinidom, TrivialJSONEncoder, SearchEngine
def analysis_new(request, analysis_id=0):
if request.method == "POST":
form = AnalysisForm(request.POST)
if form.is_valid():
model_instance = form.save()
model_instance.visible = True
weight_scenarios = model_instance.methodology_version.weight_scenario_set.filter(active=True)
if len(weight_scenarios) == 1:
model_instance.weight_scenario = weight_scenarios[0]
else:
raise Exception("There should be exactly one active WeightScenario for MethodologyVersion " + str(model_instance.methodology_version.id))
model_instance.protected = False
model_instance.created = timezone.now()
model_instance.save()
return HttpResponseRedirect(reverse('analysis_list'))
return render(request, 'analysis/analysis_new.html', {'form': form})
else:
if analysis_id>0:
analysis = get_object_or_404(Analysis, pk=analysis_id)
form = AnalysisForm(request.POST or None, instance = analysis)
return render(request, 'analysis/analysis_new.html', {'form': form, 'analysis': analysis})
else:
form = AnalysisForm()
return render(request, 'analysis/analysis_new.html', {'form': form})
class AnalysisList(ListView):
queryset = Analysis.objects.order_by('-created')
context_object_name = 'analises_list'
def detail(request, analysis_id):
analysis = get_object_or_404(Analysis, pk=analysis_id)
entity = analysis.methodology_version.methodology.entity
weight_scenarios = analysis.methodology_version.weightscenario_set.all()
exec("from " + entity.actual_entity_app + ".views import search_html_form, instance_list_html")
#"Content-Type: text/html; charset=utf-8" has to be removed as these methods return just a partial
search_html_ui = str(search_html_form(request, analysis_id))[len("Content-Type: text/html; charset=utf-8"):]
analysis_detail = str(instance_list_html(request, analysis_id))[len("Content-Type: text/html; charset=utf-8"):]
return render(request, 'analysis/analysis_detail.html', {'analysis': analysis, 'analysis_detail': analysis_detail, 'search_html_ui': search_html_ui, 'weight_scenarios': weight_scenarios})
def analysis_questions(request, analysis_id):
analysis = get_object_or_404(Analysis, pk=analysis_id)
entity = analysis.methodology_version.methodology.entity
exec("from " + entity.actual_entity_app + ".views import search_html_form, instance_list_html")
#"Content-Type: text/html; charset=utf-8" has to be removed as these methods return just a partial
analysis_detail = str(instance_list_html(request, analysis_id))[len("Content-Type: text/html; charset=utf-8"):]
return render(request, 'analysis/analysis_questions.html', {'analysis': analysis, 'analysis_detail': analysis_detail, 'methodology_version': analysis.methodology_version})
def analysis_report(request, analysis_id, weight_scenario_id = 0):
analysis = get_object_or_404(Analysis, pk=analysis_id)
weight_scenario = analysis.calculate_scores(weight_scenario_id)
td_width = 100 / (1 + len(analysis.instance_set.all()))
trend_script = "<script type=\"text/javascript\" src=\"//www.google.com/trends/embed.js?hl=it&q="
comma = ""
for instance in analysis.instance_set.all():
trend_script += comma + instance.name
comma = ","
# trend_script += "eucalyptus,+OpenNebula,+OpenStack,+Mozilla+Firefox"
trend_script += "&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330\"></script>"
return render(request, 'analysis/analysis_report.html', {'analysis': analysis, 'td_width': td_width, 'trend_script': trend_script, 'weight_scenario': weight_scenario})
def save_answer(request):
try:
question_id = request.POST.get("question_id", "")
id_selected_instance = request.POST.get("id_selected_instance", "")
value = request.POST.get("value", "")
notes = request.POST.get("notes", "")
# I look for an answer for the same question and instance
try:
a = Answer.objects.get(instance_id=id_selected_instance, question_id=question_id)
except:
# I didn't find one; let's create it
a = Answer()
a.instance = Instance.objects.get(pk=id_selected_instance)
a.question = Question.objects.get(pk=question_id)
a.value_integer = value
a.notes = notes
a.save()
except Exception as ex:
return HttpResponse(simplejson.dumps({'response': ex.message}))
return HttpResponse(simplejson.dumps({'response': 'OK', 'question_id': question_id}))
def get_answers(request):
id_instance = request.GET.get("id_instance", "")
answers = Answer.objects.filter(instance_id=id_instance)
return HttpResponse(TrivialJSONEncoder().encode(list(answers)))
def get_metadata(request):
metadata = []
id_instance = request.GET.get("id_instance", "")
instance = Instance.objects.get(pk = id_instance)
entity = instance.analysis.methodology_version.methodology.entity
#list of questions; just a plain list, I do not care in which page they are
list_of_questions = []
pages = Page.objects.filter(methodology_version = instance.analysis.methodology_version)
for page in pages:
list_of_questions += page.questions()
#all metadata about this instance
i = instance.actual_instance.getInstanceInfo()
#eval python; python code assumes that all the information is in a structure called "i" which stands for "instance"
for question in list_of_questions:
description = ""
value = -1
#run queries on search engine
for query in question.query_set.all():
description=""
# eval_text defines the variable "description"
exec(query.eval_text)
sites = []
# eval_site defines the variable "sites"
exec(query.eval_site)
search_count = str(SearchEngine.search_count(q, sites))
search_url = SearchEngine.search_url(q, sites)
search_engine_name = SearchEngine.search__engine_name()
description += "<a target='_blank' href='" + search_url + "'>'" + SearchEngine.readable_query(q, sites) + "' on " + search_engine_name + ": (" + search_count + " results)</a><br>"
# eval_description and eval_value might use the results from the above queries so have to be run after them
exec(question.eval_description)
exec(question.eval_value)
q = {}
q["question_id"] = question.id
print "question.id: " + str(question.id)
q["description"] = description
q["value"] = value
metadata.append(q)
#restituire la lista delle domande con le elaborazioni allegate
# answers = Answer.objects.filter(instance_id=id_instance)
return HttpResponse(TrivialJSONEncoder().encode(list(metadata)))
def export(request, analysis_id):
a = get_object_or_404(Analysis, pk=analysis_id)
mv = a.methodology_version
exported_xml = "<osseval>" + a.to_xml() + mv.to_xml() + "</osseval>"
return render(request, 'analysis/export.xml', {'xml': exported_xml}, content_type="application/xhtml+xml")
def upload_page(request):
message = ''
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
xml_uploaded = request.FILES['file'].read()
new_uploaded_file = UploadedFile(docfile = request.FILES['file'])
# we save it on disk so that we can process it after the user has told us which part to import and how to import it
new_uploaded_file.save()
# we parse it so that we check what is on the file against what is on the database and we show this info to the user
try:
xmldoc = minidom.parseString(xml_uploaded)
analysis_on_file = Analysis()
analysis_xml = xmldoc.getElementsByTagName('Analysis')
analysis_on_file.id = int(analysis_xml[0].attributes["Id"].firstChild.data)
analysis_on_file.name = analysis_xml[0].attributes["Name"].firstChild.data
analysis_on_file.created = analysis_xml[0].attributes["Created"].firstChild.data
analysis_on_file.user_login = analysis_xml[0].attributes["UserLogin"].firstChild.data
analysis_on_db = Analysis()
try:
analysis_on_db = Analysis.objects.get(pk=analysis_on_file.id)
except:
pass
methodology_on_file = Methodology()
methodology_version_on_file = MethodologyVersion()
methodology_version_on_file.methodology = methodology_on_file
methodology_version_xml = xmldoc.getElementsByTagName('MethodologyVersion')
methodology_version_on_file.id = xmlMinidom.getNaturalAttribute(methodology_version_xml, 'Id')
methodology_version_on_file.number = methodology_version_xml[0].attributes["Number"].firstChild.data
methodology_xml = methodology_version_xml[0].getElementsByTagName('Methodology')
methodology_on_file.id = xmlMinidom.getNaturalAttribute(methodology_xml, 'Id')
methodology_on_file.name = methodology_xml[0].attributes["Name"].firstChild.data
analysis_on_file.methodology_version = methodology_version_on_file
import_choice_form = ImportChoice(initial={'uploaded_file_id': new_uploaded_file.id, 'new_uploaded_file_relpath': new_uploaded_file.docfile.url}) # An unbound form
return render(request, 'analysis/import_file.html', {'prettyxml': xmldoc.toprettyxml(indent=" "),'file': request.FILES['file'], 'analysis_on_file': analysis_on_file, 'analysis_on_db': analysis_on_db, 'new_uploaded_file': new_uploaded_file, 'import_choice_form': import_choice_form})
except Exception as ex:
message = 'Error parsing uploaded file: ' + str(ex)
else:
form = UploadFileForm()
return render_to_response('analysis/upload_page.html', {'form': form, 'message': message}, context_instance=RequestContext(request))
def perform_import(request):
new_uploaded_file_relpath = request.POST["new_uploaded_file_relpath"]
# how_to_import = true ==> always_insert
always_insert = (int(request.POST.get("how_to_import", "")) == 1)
import_methodology = request.POST.get("import_methodology", "")
import_analysis = request.POST.get("import_analysis", "")
with open(settings.BASE_DIR + "/" + new_uploaded_file_relpath, 'r') as content_file:
xml_uploaded = content_file.read()
xmldoc = minidom.parseString(xml_uploaded)
# I assume there's only one
methodology_version_xml = xmldoc.getElementsByTagName('MethodologyVersion')[0]
mv = MethodologyVersion()
if import_methodology:
mv.from_xml(methodology_version_xml, always_insert)
else:
#If I am not importing the methodology I still need to associate it to the analysis
mv.id = methodology_version_xml.attributes["Id"].firstChild.data
a = Analysis()
a.methodology_version = mv
analysis_xml = xmldoc.getElementsByTagName('Analysis')[0]
if import_analysis:
a.from_xml(analysis_xml, always_insert)
return HttpResponseRedirect(reverse('analysis_detail', args=(a.id,)))
else:
a.id = analysis_xml.attributes["Id"].firstChild.data
return HttpResponseRedirect(reverse('analysis_list'))
def create_a_my_model(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
# save the model to database, directly from the form:
my_model = form.save() # reference to my_model is often not needed at all, a simple form.save() is ok
# alternatively:
# my_model = form.save(commit=False) # create model, but don't save to database
# my.model.something = whatever # if I need to do something before saving it
# my.model.save()
else:
form = MyModelForm()
c = { 'form' : form }
return render(request, 'analysis/template.html', c)