Skip to content

Commit

Permalink
Read paginated results
Browse files Browse the repository at this point in the history
  • Loading branch information
Xowap committed Aug 12, 2015
1 parent 05a53c2 commit 641f1f4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
32 changes: 32 additions & 0 deletions dopy/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,43 @@

import requests
import json as json_module
from six import wraps

API_ENDPOINT = 'https://api.digitalocean.com'

class DoError(RuntimeError):
pass


def paginated(func):
@wraps(func)
def wrapper(self, url, headers=None, params=None, method='GET'):
if method != 'GET':
return func(self, url, headers, params, method)

nxt = url
out = {}

while nxt is not None:
result = func(self, nxt, headers, params, 'GET')
nxt = None

if isinstance(result, dict):
for key, value in result.items():
if key in out and isinstance(out[key], list):
out[key].extend(value)
else:
out[key] = value

if 'links' in result \
and 'pages' in result['links'] \
and 'next' in result['links']['pages']:
nxt = result['links']['pages']['next']

return out
return wrapper


class DoManager(object):

def __init__(self, client_id, api_key, api_version=1):
Expand Down Expand Up @@ -451,6 +482,7 @@ def request_v1(self, url, params={}, method='GET'):

return json

@paginated
def request_v2(self, url, headers=None, params=None, method='GET'):
if headers is None:
headers = {}
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
requests>=1.0.4
six>=1.9.0

0 comments on commit 641f1f4

Please sign in to comment.