diff options
Diffstat (limited to 'src/mailman/rest/helpers.py')
| -rw-r--r-- | src/mailman/rest/helpers.py | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/src/mailman/rest/helpers.py b/src/mailman/rest/helpers.py index 197e74362..3b64dc0dc 100644 --- a/src/mailman/rest/helpers.py +++ b/src/mailman/rest/helpers.py @@ -38,8 +38,10 @@ from cStringIO import StringIO from datetime import datetime, timedelta from flufl.enum import Enum from lazr.config import as_boolean +from restish import http from restish.http import Response from restish.resource import MethodDecorator +from urllib2 import HTTPError from webob.multidict import MultiDict from mailman.config import config @@ -105,6 +107,45 @@ def etag(resource): return json.dumps(resource, cls=ExtendedEncoder) +def paginate(method): + """Method decorator to paginate through collection result lists. + + Use this to return only a slice of a collection, specified either + in the request itself or by the ``default_count`` argument. + ``default_count=None`` will return the whole collection if the request + contains no count/page parameters. + + :param default_count: The default page length if no count is specified. + :type default_count: int + :returns: Decorator function. + """ + def wrapper(*args, **kwargs): + # args[0] is self. + # restish Request object is expected to be the second arg. + request = args[1] + # get the result + result = method(*args, **kwargs) + try: + count = int(request.GET['count']) + page = int(request.GET['page']) + # Set indices + list_start = 0 + list_end = None + # slice list only if count is not None + if count is not None: + list_start = int((page - 1) * count) + list_end = int(page * count) + return result[list_start:list_end] + # Wrong parameter types or no GET attribute in request object. + except (AttributeError, ValueError, TypeError): + return http.bad_request([], b'Invalid parameters') + # No count/page params + except KeyError: + pass + return result + return wrapper + + class CollectionMixin: """Mixin class for common collection-ish things.""" |
