|
1 |
| -import os, json, requests |
| 1 | +import json |
| 2 | +import os |
| 3 | +import requests |
2 | 4 | from collections import OrderedDict
|
3 | 5 |
|
4 | 6 | API_URL = 'https://api.airtable.com/v%s/'
|
@@ -35,7 +37,7 @@ def create_payload(data):
|
35 | 37 | return {'fields': data}
|
36 | 38 |
|
37 | 39 |
|
38 |
| -class Airtable: |
| 40 | +class Airtable(object): |
39 | 41 | def __init__(self, base_id, api_key):
|
40 | 42 | self.airtable_url = API_URL % API_VERSION
|
41 | 43 | self.base_url = os.path.join(self.airtable_url, base_id)
|
@@ -68,11 +70,34 @@ def get(self, table_name, record_id=None, limit=0, offset=None):
|
68 | 70 | else:
|
69 | 71 | url = table_name
|
70 | 72 | if limit and check_integer(limit):
|
71 |
| - params.update({'limit': limit}) |
| 73 | + params.update({'pageSize': limit}) |
72 | 74 | if offset and check_string(offset):
|
73 | 75 | params.update({'offset': offset})
|
74 | 76 | return self.__request('GET', url, params)
|
75 | 77 |
|
| 78 | + def iterate(self, table_name, batch_size=0): |
| 79 | + """Iterate over all records of a table. |
| 80 | +
|
| 81 | + Args: |
| 82 | + table_name: the name of the table to list. |
| 83 | + batch_size: the number of records to fetch per request. The default |
| 84 | + (0) is using the default of the API which is (as of 2016-09) |
| 85 | + 100. Note that the API does not allow more than that (but |
| 86 | + allow for less). |
| 87 | + Yields: |
| 88 | + A dict for each record containing at least three fields: "id", |
| 89 | + "createdTime" and "fields". |
| 90 | + """ |
| 91 | + offset = None |
| 92 | + while True: |
| 93 | + response = self.get(table_name, limit=batch_size, offset=offset) |
| 94 | + for record in response.pop('records'): |
| 95 | + yield record |
| 96 | + if 'offset' in response: |
| 97 | + offset = response['offset'] |
| 98 | + else: |
| 99 | + break |
| 100 | + |
76 | 101 | def create(self, table_name, data):
|
77 | 102 | if check_string(table_name):
|
78 | 103 | payload = create_payload(data)
|
|
0 commit comments