]> git-server-git.apps.pok.os.sepia.ceph.com Git - ceph-ci.git/commitdiff
restful: Add pagination support
authorBoris Ranto <branto@redhat.com>
Fri, 19 May 2017 13:58:40 +0000 (15:58 +0200)
committerBoris Ranto <branto@redhat.com>
Mon, 22 May 2017 17:21:28 +0000 (19:21 +0200)
This commit adds a pagination support via paginate decorator. The
decorator will paginate the output if it is told to. The first page is
0, the last page is -1. The decorator was applied to /request endpoint
so you can get requests in hunderds if you supply the endpoint with
?page=N. If no ?page=N is supplied, the decorator will output the full
list.

Signed-off-by: Boris Ranto <branto@redhat.com>
src/pybind/mgr/restful/api/request.py
src/pybind/mgr/restful/decorators.py

index 3c4dd7abca8be0f2655ded933cfd231b2f5d54fc..b22b80bff8a45104cd2a32feb25f6f9f2d58246c 100644 (file)
@@ -2,7 +2,7 @@ from pecan import expose, request, response
 from pecan.rest import RestController
 
 from restful import module
-from restful.decorators import auth, lock
+from restful.decorators import auth, lock, paginate
 
 
 class RequestId(RestController):
@@ -48,6 +48,7 @@ class RequestId(RestController):
 
 class Request(RestController):
     @expose(template='json')
+    @paginate
     @auth
     def get(self, **kwargs):
         """
index 09fa64dca5360bac25040c67053f97af75918338..e5d7d62ae87ce779117ddcc6cef4b75334b53544 100644 (file)
@@ -41,3 +41,37 @@ def lock(f):
         with module.instance.requests_lock:
             return f(*args, **kwargs)
     return decorated
+
+
+# Support ?page=N argument
+def paginate(f):
+    @wraps(f)
+    def decorated(*args, **kwargs):
+        _out = f(*args, **kwargs)
+
+        # Do not modify anything without a specific request
+        if not 'page' in kwargs:
+            return _out
+
+        # A pass-through for errors, etc
+        if not isinstance(_out, list):
+            return _out
+
+        # Parse the page argument
+        _page = kwargs['page']
+        try:
+            _page = int(_page)
+        except ValueError:
+            response.status = 500
+            return {'message': 'The requested page is not an integer'}
+
+        # Raise _page so that 0 is the first page and -1 is the last
+        _page += 1
+
+        if _page > 0:
+            _page *= 100
+        else:
+            _page = len(_out) - (_page*100)
+
+        return _out[_page - 100: _page]
+    return decorated