diff options
| author | Barry Warsaw | 2013-03-21 09:52:31 -0700 |
|---|---|---|
| committer | Barry Warsaw | 2013-03-21 09:52:31 -0700 |
| commit | 2b9b4feff3845cd1eb6799037d8516510608e1a0 (patch) | |
| tree | 0cb38a04f433595129f0226b3d15a42fd0263185 /src/mailman/rest/helpers.py | |
| parent | bc4776ba20441810f2ff22d8436f450d4be2b439 (diff) | |
| parent | c8c7c3e95088db4b6e9e8b7d58094fe2818b622b (diff) | |
| download | mailman-2b9b4feff3845cd1eb6799037d8516510608e1a0.tar.gz mailman-2b9b4feff3845cd1eb6799037d8516510608e1a0.tar.zst mailman-2b9b4feff3845cd1eb6799037d8516510608e1a0.zip | |
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.""" |
