app/soc/views/helper/surveys.py
changeset 2478 985fd974e095
parent 2470 6c3b7dd8b770
child 2483 be8a113ee021
equal deleted inserted replaced
2477:e5629995d118 2478:985fd974e095
    23   '"Lennard de Rijk" <ljvderijk@gmail.com>',
    23   '"Lennard de Rijk" <ljvderijk@gmail.com>',
    24   ]
    24   ]
    25 
    25 
    26 
    26 
    27 from itertools import chain
    27 from itertools import chain
       
    28 import csv
    28 import datetime
    29 import datetime
    29 import logging
    30 import logging
       
    31 import StringIO
    30 
    32 
    31 from google.appengine.ext.db import djangoforms
    33 from google.appengine.ext.db import djangoforms
    32 
    34 
    33 from django import forms
    35 from django import forms
    34 from django.forms import widgets
    36 from django.forms import widgets
   664       gradeField.show_hidden_initial = True
   666       gradeField.show_hidden_initial = True
   665 
   667 
   666     survey_form.fields.insert(field_count + 1, 'grade', gradeField)
   668     survey_form.fields.insert(field_count + 1, 'grade', gradeField)
   667 
   669 
   668   return survey_form
   670   return survey_form
       
   671 
       
   672 
       
   673 class HelperForm(object):
       
   674   """Thin wrapper for adding values to params['edit_form'].fields.
       
   675   """
       
   676 
       
   677   def __init__(self, form=None):
       
   678     """Store the edit_form.
       
   679     """
       
   680 
       
   681     self.form = form
       
   682 
       
   683   def __call__(self, instance=None):
       
   684     """Transparently instantiate and add initial values to the edit_form.
       
   685     """
       
   686 
       
   687     form = self.form(instance=instance)
       
   688     form.fields['created_by'].initial = instance.author.name
       
   689     form.fields['last_modified_by'].initial = instance.modified_by.name
       
   690     form.fields['doc_key_name'].initial = instance.key().id_or_name()
       
   691     return form
       
   692 
       
   693 
       
   694 def _get_csv_header(sur):
       
   695   """CSV header helper, needs support for comment lines in CSV.
       
   696 
       
   697   Args:
       
   698       sur: Survey entity
       
   699   """
       
   700 
       
   701   tpl = '# %s: %s\n'
       
   702 
       
   703   # add static properties
       
   704   fields = ['# Melange Survey export for \n#  %s\n#\n' % sur.title]
       
   705   fields += [tpl % (k,v) for k,v in sur.toDict().items()]
       
   706   fields += [tpl % (f, str(getattr(sur, f))) for f in PLAIN.split()]
       
   707   fields += [tpl % (f, str(getattr(sur, f).link_id)) for f in FIELDS.split()]
       
   708   fields.sort()
       
   709 
       
   710   # add dynamic properties
       
   711   fields += ['#\n#---\n#\n']
       
   712   dynamic = sur.survey_content.dynamic_properties()
       
   713   dynamic = [(prop, getattr(sur.survey_content, prop)) for prop in dynamic]
       
   714   fields += [tpl % (k,v) for k,v in sorted(dynamic)]
       
   715 
       
   716   # add schema
       
   717   fields += ['#\n#---\n#\n']
       
   718   schema =  sur.survey_content.schema
       
   719   indent = '},\n#' + ' ' * 9
       
   720   fields += [tpl % ('Schema', schema.replace('},', indent)) + '#\n']
       
   721 
       
   722   return ''.join(fields).replace('\n', '\r\n')
       
   723 
       
   724 
       
   725 def _get_records(recs, props):
       
   726   """Fetch properties from SurveyRecords for CSV export.
       
   727   """
       
   728 
       
   729   records = []
       
   730   props = props[1:]
       
   731   for rec in recs:
       
   732     values = tuple(getattr(rec, prop, None) for prop in props)
       
   733     leading = (rec.user.link_id,)
       
   734     records.append(leading + values)
       
   735   return records
       
   736 
       
   737 
       
   738 def to_csv(survey):
       
   739   """CSV exporter.
       
   740   """
       
   741 
       
   742   # get header and properties
       
   743   header = _get_csv_header(survey)
       
   744   leading = ['user', 'created', 'modified']
       
   745   properties = leading + survey.survey_content.orderedProperties()
       
   746 
       
   747   try:
       
   748     first = survey.getRecords().run().next()
       
   749   except StopIteration:
       
   750     # bail out early if survey_records.run() is empty
       
   751     return header, survey.link_id
       
   752 
       
   753   # generate results list
       
   754   recs = survey.getRecords().run()
       
   755   recs = _get_records(recs, properties)
       
   756 
       
   757   # write results to CSV
       
   758   output = StringIO.StringIO()
       
   759   writer = csv.writer(output)
       
   760   writer.writerow(properties)
       
   761   writer.writerows(recs)
       
   762 
       
   763   return header + output.getvalue(), survey.link_id