Several style fixes and code cleaning for surveys.
authorLennard de Rijk <ljvderijk@gmail.com>
Wed, 15 Jul 2009 15:07:01 +0200
changeset 2658 34b414a80d42
parent 2657 a93c6b2acf9b
child 2659 8df08a3b17db
Several style fixes and code cleaning for surveys.
app/soc/models/project_survey_record.py
app/soc/views/helper/surveys.py
app/soc/views/models/survey.py
--- a/app/soc/models/project_survey_record.py	Wed Jul 15 12:20:48 2009 +0200
+++ b/app/soc/models/project_survey_record.py	Wed Jul 15 15:07:01 2009 +0200
@@ -40,7 +40,7 @@
   project = db.ReferenceProperty(
       reference_class=soc.models.student_project.StudentProject,
       required=True, collection_name="survey_records")
-  
+
   #: A many:1 relationship associating ProjectSurveyRecords 
   #: with specific Organization. The back-reference in the 
   #: Organization model is a Query named 'survey_records'.
--- a/app/soc/views/helper/surveys.py	Wed Jul 15 12:20:48 2009 +0200
+++ b/app/soc/views/helper/surveys.py	Wed Jul 15 15:07:01 2009 +0200
@@ -995,7 +995,7 @@
   return records
 
 
-def to_csv(survey_view):
+def toCSV(survey_view):
   """CSV exporter.
 
   Args:
--- a/app/soc/views/models/survey.py	Wed Jul 15 12:20:48 2009 +0200
+++ b/app/soc/views/models/survey.py	Wed Jul 15 15:07:01 2009 +0200
@@ -53,34 +53,37 @@
 from soc.views.models import base
 
 
-CHOICE_TYPES = set(('selection', 'pick_multi', 'choice', 'pick_quant'))
-TEXT_TYPES = set(('long_answer', 'short_answer'))
-PROPERTY_TYPES = tuple(CHOICE_TYPES) + tuple(TEXT_TYPES)
+DEF_CHOICE_TYPES = set(('selection', 'pick_multi', 'choice', 'pick_quant'))
+DEF_TEXT_TYPES = set(('long_answer', 'short_answer'))
+DEF_PROPERTY_TYPES = tuple(DEF_CHOICE_TYPES) + tuple(DEF_TEXT_TYPES)
 
 # used in View.getSchemaOptions to map POST values
-BOOL = {'True': True, 'False': False}
+DEF_BOOL = {'True': True, 'False': False}
 
-_short_answer = ("Short Answer",
-                "Less than 40 characters. Rendered as a text input. "
-                "It's possible to add a free form question (Content) "
-                "and a in-input prompt/example text.")
-_choice = ("Selection",
-           "Can be set as a single choice (selection) or multiple choice "
-           "(pick_multi) question. Rendered as a select (single choice) "
-           "or a group of checkboxes (multiple choice). It's possible to "
-           "add a free form question (Content) and as many free form options "
-           "as wanted. Each option can be edited (double-click), deleted "
-           "(click on (-) button) or reordered (drag and drop).")
-_long_answer = ("Long Answer",
-                "Unlimited length, auto-growing field. Rendered as a textarea. "
-                 "It's possible to add a free form question (Content) and "
-                 "an in-input prompt/example text.")
-QUESTION_TYPES = dict(short_answer=_short_answer, long_answer=_long_answer,
-                      choice=_choice)
+DEF_SHORT_ANSWER = ("Short Answer",
+                    "Less than 40 characters. Rendered as a text input. "
+                    "It's possible to add a free form question (Content) "
+                    "and a in-input prompt/example text.")
+DEF_CHOICE = (
+    "Selection",
+    "Can be set as a single choice (selection) or multiple choice "
+    "(pick_multi) question. Rendered as a select (single choice) "
+    "or a group of checkboxes (multiple choice). It's possible to "
+    "add a free form question (Content) and as many free form options "
+    "as wanted. Each option can be edited (double-click), deleted "
+    "(click on (-) button) or reordered (drag and drop).")
+DEF_LONG_ANSWER = (
+    "Long Answer",
+    "Unlimited length, auto-growing field. Rendered as a textarea. "
+    "It's possible to add a free form question (Content) and an in-input "
+    "prompt/example text.")
 
-# for to_csv and View.exportSerialized
-FIELDS = 'author modified_by'
-PLAIN = 'is_featured content created modified'
+DEF_QUESTION_TYPES = dict(short_answer=DEF_SHORT_ANSWER,
+                          long_answer=DEF_LONG_ANSWER, choice=DEF_CHOICE)
+
+# for toCSV and View.exportSerialized
+DEF_FIELDS = 'author modified_by'
+DEF_PLAIN = 'is_featured content created modified'
 
 
 class View(base.View):
@@ -130,7 +133,7 @@
 
     new_params['export_content_type'] = 'text/text'
     new_params['export_extension'] = '.csv'
-    new_params['export_function'] = surveys.to_csv(self)
+    new_params['export_function'] = surveys.toCSV(self)
     new_params['delete_redirect'] = '/'
     new_params['list_key_order'] = [
         'link_id', 'scope_path', 'name', 'short_name', 'title',
@@ -141,7 +144,7 @@
     new_params['public_template'] = 'soc/survey/public.html'
     new_params['take_template'] = 'soc/survey/take.html'
 
-    # TODO which one of these are leftovers from Document?
+    # TODO: which one of these are leftovers from Document?
     new_params['no_create_raw'] = True
     new_params['no_create_with_scope'] = True
     new_params['no_create_with_key_fields'] = True
@@ -281,7 +284,7 @@
         if question_name not in schema:
           continue
 
-        if schema[question_name]['type'] not in CHOICE_TYPES:
+        if schema[question_name]['type'] not in DEF_CHOICE_TYPES:
           # Choice questions are always regenerated from request, see
           # self.get_request_questions()
           question = getattr(survey_content, question_name)
@@ -329,7 +332,7 @@
             # new Choice question, set generic type and get its index
             schema[name] = {'type': 'choice'}
 
-        if name in schema and schema[name]['type'] in CHOICE_TYPES:
+        if name in schema and schema[name]['type'] in DEF_CHOICE_TYPES:
           # build an index:content dictionary
           if name in survey_fields:
             if value not in survey_fields[name]:
@@ -348,7 +351,7 @@
         field_name = prefix.sub('', key)
         field = 'id_' + key
 
-        for ptype in PROPERTY_TYPES:
+        for ptype in DEF_PROPERTY_TYPES:
           # should only match one
           if ptype + "__" in field_name:
             field_name = field_name.replace(ptype + "__", "")
@@ -375,7 +378,7 @@
                     'radio_buttons': 'pick_quant' }
 
     for key in schema:
-      if schema[key]['type'] in CHOICE_TYPES and key in survey_fields:
+      if schema[key]['type'] in DEF_CHOICE_TYPES and key in survey_fields:
         render_for = 'render_for_' + key
         if render_for in POST:
           schema[key]['render'] = RENDER[POST[render_for]]
@@ -415,11 +418,11 @@
 
       # set wheter the question is required
       required_for = 'required_for_' + key
-      schema[key]['required'] = BOOL[POST[required_for]]
+      schema[key]['required'] = DEF_BOOL[POST[required_for]]
 
       # set wheter the question allows comments
       comment_for = 'comment_for_' + key
-      schema[key]['has_comment'] = BOOL[POST[comment_for]]
+      schema[key]['has_comment'] = DEF_BOOL[POST[comment_for]]
 
       # set the question index from JS-calculated value
       index_for = 'index_for_' + key
@@ -430,7 +433,7 @@
     """Pass the question types for the survey creation template.
     """
 
-    context['question_types'] = QUESTION_TYPES
+    context['question_types'] = DEF_QUESTION_TYPES
 
     # avoid spurious results from showing on creation
     context['new_survey'] = True
@@ -449,7 +452,7 @@
                                          survey_logic=params['logic'])
     survey_form.getFields()
 
-    local = dict(survey_form=survey_form, question_types=QUESTION_TYPES,
+    local = dict(survey_form=survey_form, question_types=DEF_QUESTION_TYPES,
                 survey_h=entity.survey_content)
     context.update(local)
 
@@ -647,31 +650,18 @@
           survey.survey_end.strftime("%A, %d. %B %Y %I:%M%p"))
 
     if survey_record:
-      help_text = "You may edit and re-submit this survey" + survey_end_text + "."
+      help_text = "You may edit and re-submit this survey %s." %(
+          survey_end_text)
       status = "edit"
     else:
-      help_text = "Please complete this survey" + survey_end_text + "."
+      help_text = "Please complete this survey %s." %(
+          survey_end_text)
       status = "create"
 
     # update the context with the help_text and status
     context_update = dict(status=status, help_text=help_text)
     context.update(context_update)
 
-  def activate(self, request, **kwargs):
-    """This is a hack to support the 'Enable grades' button.
-    """
-    self.activateGrades(request)
-    redirect_path = request.path.replace('/activate/', '/edit/') + '?activate=1'
-    return http.HttpResponseRedirect(redirect_path)
-
-  def activateGrades(self, request, **kwargs):
-    """Updates SurveyRecord's grades for a given Survey.
-    """
-    survey_key_name = survey_logic.getKeyNameFromPath(request.path)
-    survey = Survey.get_by_key_name(survey_key_name)
-    survey_logic.activateGrades(survey)
-    return
-
   @decorators.merge_params
   @decorators.check_access
   def viewResults(self, request, access_type, page_name=None,
@@ -727,16 +717,22 @@
   @decorators.check_access
   def exportSerialized(self, request, access_type, page_name=None,
                        params=None, **kwargs):
+    """Exports Surveys in JSON format.
 
-    sur, context = self.getContextEntity(request, page_name, params, kwargs)
+    For args see base.View.public().
+    """
 
-    if context is None:
-      # user cannot see this page, return error response
-      return sur
+    survey_logic = params['logic']
+
+    try:
+      sur = survey_logic.getFromKeyFieldsOr404(kwargs)
+    except out_of_band.Error, error:
+      return responses.errorResponse(
+          error, request, template=params['error_public'])
 
     json = sur.toDict()
-    json.update(dict((f, str(getattr(sur, f))) for f in PLAIN.split()))
-    static = ((f, str(getattr(sur, f).link_id)) for f in FIELDS.split())
+    json.update(dict((f, str(getattr(sur, f))) for f in DEF_PLAIN.split()))
+    static = ((f, str(getattr(sur, f).link_id)) for f in DEF_FIELDS.split())
     json.update(dict(static))
 
     dynamic = sur.survey_content.dynamic_properties()
@@ -751,6 +747,18 @@
     return self.json(request, data=json)
 
   def importSerialized(self, request, fields, user):
+    """Import Surveys in JSON format.
+
+    TODO: have this method do a proper import
+
+    Args:
+      request: Django Requset object
+      fields: ???
+      user: ???
+
+    Returns:
+      Keywords, the survey's schema and the survey content.
+    """
     json = request.POST['serialized']
     json = simplejson.loads(json)['data']
     survey_content = json.pop('survey_content')
@@ -758,7 +766,7 @@
     del json['author']
     del json['created']
     del json['modified']
-    #del json['is_featured']
+
     # keywords can't be unicode
     keywords = {}
     for key, val in json.items():
@@ -767,27 +775,6 @@
       keywords['is_featured'] = eval(keywords['is_featured'])
     return keywords, schema, survey_content
 
-  def getContextEntity(self, request, page_name, params, kwargs):
-    context = responses.getUniversalContext(request)
-    responses.useJavaScript(context, params['js_uses_all'])
-    context['page_name'] = page_name
-    entity = None
-
-    # TODO(ajaksu) there has to be a better way in this universe to get these
-    kwargs['prefix'] = 'program'
-    kwargs['link_id'] = request.path.split('/')[-1]
-    kwargs['scope_path'] = '/'.join(request.path.split('/')[4:-1])
-
-    entity = survey_logic.getFromKeyFieldsOr404(kwargs)
-
-    if not self._public(request, entity, context):
-      error = out_of_band.Error('')
-      error = responses.errorResponse(
-          error, request, template=params['error_public'], context=context)
-      return error, None
-
-    return entity, context
-
   def getMenusForScope(self, entity, params, id, user):
     """List featured surveys if after the survey_start date 
     and before survey_end an iff the current user has the right taking access.