Skip to content

Commit aad49b4

Browse files
committed
iterate over all results of an API call with pagination
1 parent 4723f0e commit aad49b4

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

‎PythonConfluenceAPI/__init__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
__author__ = 'Robert Cope', 'Pushrod Technology'
22

3-
from api import ConfluenceAPI
4-
from cfapi import ConfluenceFuturesAPI
3+
from api import ConfluenceAPI, all_of
4+
from cfapi import ConfluenceFuturesAPI

‎PythonConfluenceAPI/api.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
__author__ = "Robert Cope"
22

3+
import sys
34
import requests
45
from requests.auth import HTTPBasicAuth
56
from urlparse import urljoin
@@ -14,6 +15,38 @@
1415
api_logger.addHandler(nh)
1516

1617

18+
def all_of(api_call, *args, **kwargs):
19+
"""
20+
Generator that iterates over all results of an API call that requires limit/start pagination.
21+
22+
If the `limit` keyword argument is set, it is used to stop the
23+
generator after the given number of result items.
24+
25+
>>> for i, v in enumerate(all_of(api.get_content)):
26+
>>> v = bunchify(v)
27+
>>> print('\t'.join((str(i), v.type, v.id, v.status, v.title)))
28+
29+
:param api_call: Confluence API call (method).
30+
:param args: Positional arguments of the call.
31+
:param kwargs: Keyword arguments of the call.
32+
"""
33+
kwargs = kwargs.copy()
34+
pos, outer_limit = 0, kwargs.get('limit', 0) or sys.maxint
35+
while True:
36+
response = api_call(*args, **kwargs)
37+
for item in response.get('results', []):
38+
pos += 1
39+
if pos > outer_limit:
40+
return
41+
yield item
42+
##print((pos, response['start'], response['limit']))
43+
if response.get('_links', {}).get('next', None):
44+
kwargs['start'] = response['start'] + response['size']
45+
kwargs['limit'] = response['limit']
46+
else:
47+
return
48+
49+
1750
class ConfluenceAPI(object):
1851
DEFAULT_USER_AGENT = "PythonConfluenceAPI"
1952

0 commit comments

Comments
 (0)