Move soc/views/helpers/list_helpers.py to soc/views/helpers/list.py and change
authorTodd Larsen <tlarsen@google.com>
Fri, 03 Oct 2008 21:41:12 +0000
changeset 266 3b47bfd4f1b3
parent 265 3c2994f3b85f
child 267 0c008a43443b
Move soc/views/helpers/list_helpers.py to soc/views/helpers/list.py and change uses from list_helpers. to helpers.list. instead. Patch by: Todd Larsen Review by: to-be-reviewed
app/soc/views/helpers/list.py
app/soc/views/helpers/list_helpers.py
app/soc/views/site/docs/list.py
app/soc/views/site/sponsor/list.py
app/soc/views/site/user/list.py
app/soc/views/site/user/profile.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/app/soc/views/helpers/list.py	Fri Oct 03 21:41:12 2008 +0000
@@ -0,0 +1,213 @@
+#!/usr/bin/python2.5
+#
+# Copyright 2008 the Melange authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Helpers used to render lists.
+"""
+
+__authors__ = [
+  '"Chen Lunpeng" <forever.clp@gmail.com>',
+  '"Pawel Solyga" <pawel.solyga@gmail.com>',
+  ]
+
+
+from soc.views.helpers import forms_helpers
+
+
+DEF_PAGINATION = 10
+MAX_PAGINATION = 100
+
+DEF_PAGINATION_CHOICES = (
+  ('10', '10 items per page'),
+  ('25', '25 items per page'),
+  ('50', '50 items per page'),
+  ('100', '100 items per page'),
+)
+
+
+def getPreferredListPagination(user=None):
+    """Returns User's preferred list pagination limit.
+    
+    Args:
+      user: User entity containing the list pagination preference;
+        default is None, to use the current logged-in User
+    """
+    # TODO: eventually this limit should be a User profile preference
+    #   (stored in the site-wide User Model) preference 
+    return DEF_PAGINATION
+
+
+def cleanListParameters(offset=None, limit=None):
+  """Converts and validates offset and limit values of the list.
+
+  Args:
+    offset: offset in list which defines first item to return
+    limit: max amount of items per page
+
+  Returns:
+    updated offset and limit values
+  """
+  # update offset value
+  try:
+    offset = int(offset)
+  except:
+    # also catches offset=None case where offset not supplied
+    offset = 0
+
+  # update limit value
+  try:
+    limit = int(limit)
+  except:
+    # also catches limit=None case where limit not supplied
+    limit = getPreferredListPagination()
+
+  return max(0, offset), max(1, min(limit, MAX_PAGINATION))
+
+
+DEF_LIST_TEMPLATES = {'list_main': 'soc/list/list_main.html',
+                      'list_pagination': 'soc/list/list_pagination.html',
+                      'list_row': 'soc/list/list_row.html',
+                      'list_heading': 'soc/list/list_heading.html'}
+
+def setList(request, context, list_data,
+            offset=0, limit=0, list_templates=DEF_LIST_TEMPLATES):
+  """Updates template context dict with variables used for rendering lists.
+
+  Args:
+    request: the Django HTTP request object
+    context: the template context dict to be updated in-place (pass in a copy
+      if the original must not be modified), or None if a new one is to be
+      created; any existing fields already present in the context dict passed
+      in by the caller are left unaltered 
+    list_data: array of data to be displayed in the list
+    offset: offset in list which defines first item to return
+    limit: max amount of items per page
+    list_templates: templates that are used when rendering list
+
+  Returns:
+    updated template context dict supplied by the caller or a new context
+    dict if the caller supplied None
+
+    {
+      'list_data': list data to be displayed 
+      'list_main': url to list main template
+      'list_pagination': url to list pagination template
+      'list_row': url to list row template
+      'list_heading': url to list heading template
+      'limit': max amount of items per page,
+      'newest': url to first page of the list 
+      'prev': url to previous page 
+      'next': url to next page
+      'first': offset of the first item in the list
+      'last': offest of the lst item in the list
+    }
+  """  
+  if not list_data:
+    list_data = []
+  
+  more = bool(list_data[limit:])
+  if more:
+    del list_data[limit:]
+  if more:
+    next = request.path + '?offset=%d&limit=%d' % (offset+limit, limit)
+  else:
+    next = ''
+  if offset > 0:
+    prev = request.path + '?offset=%d&limit=%d' % (max(0, offset-limit), limit)
+  else:
+    prev = ''
+  newest = ''
+  if offset > limit:
+    newest = request.path + '?limit=%d' % limit
+  
+  if not context:
+    context = {}
+  
+  context.update(
+    {'list_data': list_data, 
+     'list_main': list_templates['list_main'],
+     'list_pagination': list_templates['list_pagination'],
+     'list_row': list_templates['list_row'],
+     'list_heading': list_templates['list_heading'],
+     'limit': limit,
+     'newest': newest, 
+     'prev': prev, 
+     'next': next,
+     'first': offset+1,
+     'last': len(list_data) > 1 and offset+len(list_data) or None})
+  
+  return context
+
+
+def makePaginationForm(
+  request, limit, arg_name='limit', choices=DEF_PAGINATION_CHOICES,
+  field_name_fmt=forms_helpers.DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT):
+  """Returns a customized pagination limit selection form.
+  
+  Args:
+    request: the standard Django HTTP request object
+    limit: the initial value of the selection control
+    arg_name: see forms_helpers.makeSelectQueryArgForm(); default is 'limit'
+    choices: see forms_helpers.makeSelectQueryArgForm(); default is
+      DEF_PAGINATION_CHOICES
+    field_name_fmt: see forms_helpers.makeSelectQueryArgForm()
+  """
+  choices = makeNewPaginationChoices(limit=limit, choices=choices)
+  
+  return forms_helpers.makeSelectQueryArgForm(
+      request, arg_name, limit, choices)
+
+
+def makeNewPaginationChoices(limit=DEF_PAGINATION,
+                             choices=DEF_PAGINATION_CHOICES):
+  """Updates the pagination limit selection form.
+
+  Args:
+    limit: the initial value of the selection control;
+      default is DEF_PAGINATION
+    choices: see forms_helpers.makeSelectQueryArgForm();
+      default is DEF_PAGINATION_CHOICES
+
+  Returns:
+    a new pagination choices list if limit is not in
+    DEF_PAGINATION_CHOICES, or DEF_PAGINATION_CHOICES otherwise
+  """
+  # determine where to insert the new limit into choices
+  new_choices = []
+  inserted = False
+  
+  for pagination, label in choices:
+    items = int(pagination)
+
+    if limit == items:
+      # limit is already present, so just return existing choices
+      return choices
+
+    if (not inserted) and (limit < items):
+      # limit needs to be inserted before the current pagination,
+      # so assemble a new choice tuple and append it 
+      choice = (str(limit), '%s items per page' % limit)
+      new_choices.append(choice)
+      inserted = True
+      
+    # append the existing choice
+    new_choices.append((pagination, label))
+
+  if not inserted:
+    # new choice must go last, past all other existing choices
+    choice = (str(limit), '%s items per page' % limit)
+    new_choices.append(choice)
+      
+  return new_choices
--- a/app/soc/views/helpers/list_helpers.py	Fri Oct 03 17:21:41 2008 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,213 +0,0 @@
-#!/usr/bin/python2.5
-#
-# Copyright 2008 the Melange authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Helpers used to render lists.
-"""
-
-__authors__ = [
-  '"Chen Lunpeng" <forever.clp@gmail.com>',
-  '"Pawel Solyga" <pawel.solyga@gmail.com>',
-  ]
-
-
-from soc.views.helpers import forms_helpers
-
-
-DEF_PAGINATION = 10
-MAX_PAGINATION = 100
-
-DEF_PAGINATION_CHOICES = (
-  ('10', '10 items per page'),
-  ('25', '25 items per page'),
-  ('50', '50 items per page'),
-  ('100', '100 items per page'),
-)
-
-
-def getPreferredListPagination(user=None):
-    """Returns User's preferred list pagination limit.
-    
-    Args:
-      user: User entity containing the list pagination preference;
-        default is None, to use the current logged-in User
-    """
-    # TODO: eventually this limit should be a User profile preference
-    #   (stored in the site-wide User Model) preference 
-    return DEF_PAGINATION
-
-
-def cleanListParameters(offset=None, limit=None):
-  """Converts and validates offset and limit values of the list.
-
-  Args:
-    offset: offset in list which defines first item to return
-    limit: max amount of items per page
-
-  Returns:
-    updated offset and limit values
-  """
-  # update offset value
-  try:
-    offset = int(offset)
-  except:
-    # also catches offset=None case where offset not supplied
-    offset = 0
-
-  # update limit value
-  try:
-    limit = int(limit)
-  except:
-    # also catches limit=None case where limit not supplied
-    limit = getPreferredListPagination()
-
-  return max(0, offset), max(1, min(limit, MAX_PAGINATION))
-
-
-DEF_LIST_TEMPLATES = {'list_main': 'soc/list/list_main.html',
-                      'list_pagination': 'soc/list/list_pagination.html',
-                      'list_row': 'soc/list/list_row.html',
-                      'list_heading': 'soc/list/list_heading.html'}
-
-def setList(request, context, list_data,
-            offset=0, limit=0, list_templates=DEF_LIST_TEMPLATES):
-  """Updates template context dict with variables used for rendering lists.
-
-  Args:
-    request: the Django HTTP request object
-    context: the template context dict to be updated in-place (pass in a copy
-      if the original must not be modified), or None if a new one is to be
-      created; any existing fields already present in the context dict passed
-      in by the caller are left unaltered 
-    list_data: array of data to be displayed in the list
-    offset: offset in list which defines first item to return
-    limit: max amount of items per page
-    list_templates: templates that are used when rendering list
-
-  Returns:
-    updated template context dict supplied by the caller or a new context
-    dict if the caller supplied None
-
-    {
-      'list_data': list data to be displayed 
-      'list_main': url to list main template
-      'list_pagination': url to list pagination template
-      'list_row': url to list row template
-      'list_heading': url to list heading template
-      'limit': max amount of items per page,
-      'newest': url to first page of the list 
-      'prev': url to previous page 
-      'next': url to next page
-      'first': offset of the first item in the list
-      'last': offest of the lst item in the list
-    }
-  """  
-  if not list_data:
-    list_data = []
-  
-  more = bool(list_data[limit:])
-  if more:
-    del list_data[limit:]
-  if more:
-    next = request.path + '?offset=%d&limit=%d' % (offset+limit, limit)
-  else:
-    next = ''
-  if offset > 0:
-    prev = request.path + '?offset=%d&limit=%d' % (max(0, offset-limit), limit)
-  else:
-    prev = ''
-  newest = ''
-  if offset > limit:
-    newest = request.path + '?limit=%d' % limit
-  
-  if not context:
-    context = {}
-  
-  context.update(
-    {'list_data': list_data, 
-     'list_main': list_templates['list_main'],
-     'list_pagination': list_templates['list_pagination'],
-     'list_row': list_templates['list_row'],
-     'list_heading': list_templates['list_heading'],
-     'limit': limit,
-     'newest': newest, 
-     'prev': prev, 
-     'next': next,
-     'first': offset+1,
-     'last': len(list_data) > 1 and offset+len(list_data) or None})
-  
-  return context
-
-
-def makePaginationForm(
-  request, limit, arg_name='limit', choices=DEF_PAGINATION_CHOICES,
-  field_name_fmt=forms_helpers.DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT):
-  """Returns a customized pagination limit selection form.
-  
-  Args:
-    request: the standard Django HTTP request object
-    limit: the initial value of the selection control
-    arg_name: see forms_helpers.makeSelectQueryArgForm(); default is 'limit'
-    choices: see forms_helpers.makeSelectQueryArgForm(); default is
-      DEF_PAGINATION_CHOICES
-    field_name_fmt: see forms_helpers.makeSelectQueryArgForm()
-  """
-  choices = makeNewPaginationChoices(limit=limit, choices=choices)
-  
-  return forms_helpers.makeSelectQueryArgForm(
-      request, arg_name, limit, choices)
-
-
-def makeNewPaginationChoices(limit=DEF_PAGINATION,
-                             choices=DEF_PAGINATION_CHOICES):
-  """Updates the pagination limit selection form.
-
-  Args:
-    limit: the initial value of the selection control;
-      default is DEF_PAGINATION
-    choices: see forms_helpers.makeSelectQueryArgForm();
-      default is DEF_PAGINATION_CHOICES
-
-  Returns:
-    a new pagination choices list if limit is not in
-    DEF_PAGINATION_CHOICES, or DEF_PAGINATION_CHOICES otherwise
-  """
-  # determine where to insert the new limit into choices
-  new_choices = []
-  inserted = False
-  
-  for pagination, label in choices:
-    items = int(pagination)
-
-    if limit == items:
-      # limit is already present, so just return existing choices
-      return choices
-
-    if (not inserted) and (limit < items):
-      # limit needs to be inserted before the current pagination,
-      # so assemble a new choice tuple and append it 
-      choice = (str(limit), '%s items per page' % limit)
-      new_choices.append(choice)
-      inserted = True
-      
-    # append the existing choice
-    new_choices.append((pagination, label))
-
-  if not inserted:
-    # new choice must go last, past all other existing choices
-    choice = (str(limit), '%s items per page' % limit)
-    new_choices.append(choice)
-      
-  return new_choices
--- a/app/soc/views/site/docs/list.py	Fri Oct 03 17:21:41 2008 +0000
+++ b/app/soc/views/site/docs/list.py	Fri Oct 03 21:41:12 2008 +0000
@@ -24,7 +24,8 @@
 
 from soc.logic import works
 from soc.views import simple
-from soc.views.helpers import list_helpers
+from soc.views import helpers
+import soc.views.helpers.list
 from soc.views.helpers import response_helpers
 
 import soc.models.document
@@ -52,21 +53,21 @@
   if alt_response:
     return alt_response  
   
-  offset, limit = list_helpers.cleanListParameters(
+  offset, limit = helpers.list.cleanListParameters(
       offset=request.GET.get('offset'), limit=request.GET.get('limit'))
 
   # Fetch one more to see if there should be a 'next' link
   docs = works.getWorksForLimitAndOffset(
       limit + 1, offset=offset, cls=soc.models.document.Document)
 
-  context['pagination_form'] = list_helpers.makePaginationForm(request, limit)
+  context['pagination_form'] = helpers.list.makePaginationForm(request, limit)
 
   list_templates = {'list_main': 'soc/list/list_main.html',
                     'list_pagination': 'soc/list/list_pagination.html',
                     'list_row': 'soc/site/docs/list/docs_row.html',
                     'list_heading': 'soc/site/docs/list/docs_heading.html'}
                       
-  context = list_helpers.setList(
+  context = helpers.list.setList(
       request, context, docs, 
       offset=offset, limit=limit, list_templates=list_templates)
 
--- a/app/soc/views/site/sponsor/list.py	Fri Oct 03 17:21:41 2008 +0000
+++ b/app/soc/views/site/sponsor/list.py	Fri Oct 03 21:41:12 2008 +0000
@@ -24,7 +24,8 @@
 
 from soc.logic import sponsor
 from soc.views import simple
-from soc.views.helpers import list_helpers
+from soc.views import helpers
+import soc.views.helpers.list
 from soc.views.helpers import response_helpers
 
 
@@ -41,20 +42,20 @@
   if alt_response:
     return alt_response  
   
-  offset, limit = list_helpers.cleanListParameters(
+  offset, limit = helpers.list.cleanListParameters(
       offset=request.GET.get('offset'), limit=request.GET.get('limit'))
   
   # Fetch one more to see if there should be a 'next' link
   sponsors = sponsor.getSponsorsForLimitAndOffset(limit + 1, offset=offset)
 
-  context['pagination_form'] = list_helpers.makePaginationForm(request, limit)
+  context['pagination_form'] = helpers.list.makePaginationForm(request, limit)
   
   list_templates = {'list_main': 'soc/list/list_main.html',
                     'list_pagination': 'soc/list/list_pagination.html',
                     'list_row': 'soc/group/list/group_row.html',
                     'list_heading': 'soc/group/list/group_heading.html'}
                       
-  context = list_helpers.setList(request, context, sponsors, 
+  context = helpers.list.setList(request, context, sponsors, 
                                  offset, limit, list_templates)
                                  
   context['group_type'] = 'Sponsor'
--- a/app/soc/views/site/user/list.py	Fri Oct 03 17:21:41 2008 +0000
+++ b/app/soc/views/site/user/list.py	Fri Oct 03 21:41:12 2008 +0000
@@ -24,7 +24,8 @@
 
 from soc.logic.site import id_user
 from soc.views import simple
-from soc.views.helpers import list_helpers
+from soc.views import helpers
+import soc.views.helpers.list
 from soc.views.helpers import response_helpers
 
 import soc.models.user
@@ -52,20 +53,20 @@
   if alt_response:
     return alt_response  
   
-  offset, limit = list_helpers.cleanListParameters(
+  offset, limit = helpers.list.cleanListParameters(
       offset=request.GET.get('offset'), limit=request.GET.get('limit'))
 
   # Fetch one more to see if there should be a 'next' link
   users = id_user.getUsersForLimitAndOffset(limit + 1, offset=offset)
 
-  context['pagination_form'] = list_helpers.makePaginationForm(request, limit)
+  context['pagination_form'] = helpers.list.makePaginationForm(request, limit)
   
   list_templates = {'list_main': 'soc/list/list_main.html',
                     'list_pagination': 'soc/list/list_pagination.html',
                     'list_row': 'soc/site/user/list/user_row.html',
                     'list_heading': 'soc/site/user/list/user_heading.html'}
                       
-  context = list_helpers.setList(
+  context = helpers.list.setList(
       request, context, users,
       offset=offset, limit=limit, list_templates=list_templates)
 
--- a/app/soc/views/site/user/profile.py	Fri Oct 03 17:21:41 2008 +0000
+++ b/app/soc/views/site/user/profile.py	Fri Oct 03 21:41:12 2008 +0000
@@ -32,8 +32,9 @@
 from soc.logic import out_of_band
 from soc.logic.site import id_user
 from soc.views import simple
+from soc.views import helpers
+import soc.views.helpers.list
 from soc.views.helpers import forms_helpers
-from soc.views.helpers import list_helpers
 from soc.views.helpers import request_helpers
 from soc.views.helpers import response_helpers
 from soc.views.user import profile
@@ -129,7 +130,7 @@
           lookup_message = ugettext_lazy('User found by email.')
         else:
           email_error = ugettext_lazy('User with that email not found.')
-          range_width = list_helpers.getPreferredListPagination()
+          range_width = helpers.list.getPreferredListPagination()
           nearest_user_range_start = id_user.findNearestUsersOffset(
               range_width, id=form_id)
             
@@ -150,11 +151,11 @@
           else:
             context['linkname_error'] = ugettext_lazy(
                 'User with that link name not found.')
-            range_width = list_helpers.getPreferredListPagination()
+            range_width = helpers.list.getPreferredListPagination()
             nearest_user_range_start = id_user.findNearestUsersOffset(
                 range_width, link_name=linkname)
             
-            if nearest_user_range_start is not None:            
+            if nearest_user_range_start is not None:
               context['lookup_link'] = './list?offset=%s&limit=%s' % (
                   nearest_user_range_start, range_width)
     # else: form was not valid