|
| 1 | +from typing import Any, Dict, Iterable, Optional, TypeVar |
| 2 | + |
| 3 | +import dataclasses |
| 4 | + |
| 5 | +from django.conf import settings |
| 6 | +from rest_framework_dataclasses.field_utils import get_type_info |
| 7 | + |
| 8 | +from groundwork.core.datasources import RestDatasource |
| 9 | + |
| 10 | +ResourceT = TypeVar("ResourceT") |
| 11 | + |
| 12 | + |
| 13 | +def airtable_field(name: str, **kwargs: Dict[str, Any]) -> dataclasses.Field: |
| 14 | + """ |
| 15 | + Return a [dataclass field](https://docs.python.org/3/library/dataclasses.html#dataclasses.Field) used to annotate |
| 16 | + a Resource class with the name of the column in Airtable. |
| 17 | +
|
| 18 | + For example, if you have an Airtable like this: |
| 19 | +
|
| 20 | + | First Name | Last Name | |
| 21 | + | ----------- | ---------- | |
| 22 | + | Stafford | Beer | |
| 23 | + | Clara | Zetkin | |
| 24 | +
|
| 25 | + You could map it onto a django model like this: |
| 26 | +
|
| 27 | + ```python |
| 28 | + @dataclass |
| 29 | + class People: |
| 30 | + id: str |
| 31 | + first_name: str = airtable_field('First Name') |
| 32 | + last_name: str = airtable_field('Last Name') |
| 33 | + ``` |
| 34 | +
|
| 35 | + If you do not annotate your field like this, `AirtableDatasource` will expect your column in Airtable to have the |
| 36 | + same name as your Resource class. |
| 37 | +
|
| 38 | + Args: |
| 39 | + name: Airtable column name associated with this field. |
| 40 | + kwargs: Keyword args passed to [dataclasses.field](https://docs.python.org/3/library/dataclasses.html#dataclasses.field). |
| 41 | +
|
| 42 | + Returns: |
| 43 | + A dataclass field descriptor identifying the corresponding Airtable column. |
| 44 | +
|
| 45 | + """ |
| 46 | + metadata = {__name__: {"airtable_field": name}} |
| 47 | + metadata.update(kwargs.pop("metadata", None) or {}) |
| 48 | + |
| 49 | + return dataclasses.field(metadata=metadata, **kwargs) |
| 50 | + |
| 51 | + |
| 52 | +class AirtableDatasource(RestDatasource[ResourceT]): |
| 53 | + """ |
| 54 | + Base class for implementing clients to Airtable bases and converting their responses to resource objects. |
| 55 | +
|
| 56 | + You are encouraged to use Python's inbuilt [`@dataclass`](https://docs.python.org/3/library/dataclasses.html) |
| 57 | + decorator and define type hints when defining these classes as this allows type-safe serializers to be |
| 58 | + auto-generated and decreases the amount of boilerplate code that you need to write. |
| 59 | +
|
| 60 | + __Example:__ |
| 61 | +
|
| 62 | + Let's assume we have a public airtable with the base id `4rQYK6P56My`. It contains a table called 'Active Members', |
| 63 | + which looks like this: |
| 64 | +
|
| 65 | + | First Name | Last Name | |
| 66 | + | ----------- | ---------- | |
| 67 | + | Stafford | Beer | |
| 68 | + | Clara | Zetkin | |
| 69 | +
|
| 70 | +
|
| 71 | + We can create a datasource for it as follows: |
| 72 | +
|
| 73 | + ```python |
| 74 | + from dataclasses import dataclass |
| 75 | + from groundwork.contrib.airtable.datasources import AirtableDatasource, airtable_field |
| 76 | +
|
| 77 | + @dataclass |
| 78 | + class Person: |
| 79 | + id: str |
| 80 | + first_name: str = airtable_field('First Name') |
| 81 | + last_name: str = airtable_field('Last Name') |
| 82 | +
|
| 83 | + my_datasource = AirtableDatasource( |
| 84 | + base_id="4rQYK6P56My", |
| 85 | + table_name="Active Members", |
| 86 | + resource_class=Person, |
| 87 | + ) |
| 88 | + ``` |
| 89 | +
|
| 90 | + As with other datasource types, configuration can all either be provided as keyword-args to the constructor, or |
| 91 | + overridden in subclasses. |
| 92 | + """ |
| 93 | + |
| 94 | + base_url = "https://api.airtable.com/v0" |
| 95 | + |
| 96 | + api_key: str |
| 97 | + """ |
| 98 | + Airtable API key. Required for private Airtable bases. If not defined, will default to the value of |
| 99 | + `django.conf.settings.AIRTABLE_API_KEY`. |
| 100 | + """ |
| 101 | + |
| 102 | + base_id: Optional[str] = None |
| 103 | + """ |
| 104 | + ID of the airtable base. You can find this in your base's [API Docs](https://airtable.com/api) |
| 105 | + """ |
| 106 | + |
| 107 | + table_name: Optional[str] = None |
| 108 | + """ |
| 109 | + Name of the table to fetch from. |
| 110 | + """ |
| 111 | + |
| 112 | + def __init__(self, resource_type: ResourceT, base=None, table=None, **kwargs): |
| 113 | + super().__init__(resource_type=resource_type, **kwargs) |
| 114 | + |
| 115 | + if not getattr(self, "path", None): |
| 116 | + assert self.base_id |
| 117 | + assert self.table_name |
| 118 | + self.path = f"/{self.base_id}/{self.table_name}" |
| 119 | + |
| 120 | + if not hasattr(self, "api_key"): |
| 121 | + self.api_key = getattr(settings, "AIRTABLE_API_KEY", None) |
| 122 | + |
| 123 | + def paginate(self, **query: Dict[str, Any]) -> Iterable[ResourceT]: |
| 124 | + offset = None |
| 125 | + |
| 126 | + while True: |
| 127 | + if offset is not None: |
| 128 | + query["offset"] = offset |
| 129 | + data = self.fetch_url(self.url, query) |
| 130 | + |
| 131 | + yield from data["records"] |
| 132 | + |
| 133 | + offset = data.get("offset") |
| 134 | + if offset is None: |
| 135 | + return |
| 136 | + |
| 137 | + def deserialize(self, data: Dict[str, Any]) -> ResourceT: |
| 138 | + field_data = data["fields"] |
| 139 | + |
| 140 | + mapped_data = { |
| 141 | + field.name: self._get_mapped_field_value(field, field_data) |
| 142 | + for field in dataclasses.fields(self.resource_type) |
| 143 | + } |
| 144 | + mapped_data["id"] = data["id"] |
| 145 | + |
| 146 | + return super().deserialize(mapped_data) |
| 147 | + |
| 148 | + def get_headers(self) -> Dict[str, str]: |
| 149 | + headers = {} |
| 150 | + |
| 151 | + if self.api_key: |
| 152 | + headers["Authorization"] = f"Bearer {self.api_key}" |
| 153 | + |
| 154 | + return headers |
| 155 | + |
| 156 | + def _get_mapped_field_name(self, field: dataclasses.Field) -> str: |
| 157 | + """ |
| 158 | + Look up the mapped field name expected from the Airtable response. |
| 159 | +
|
| 160 | + Args: |
| 161 | + field: Dataclass field descriptor for the resource field |
| 162 | +
|
| 163 | + Returns: |
| 164 | + Airtable column name defined in the field's metadata. Returns the field name if none found, |
| 165 | + """ |
| 166 | + |
| 167 | + if __name__ not in field.metadata: |
| 168 | + return field.name |
| 169 | + |
| 170 | + return field.metadata[__name__]["airtable_field"] |
| 171 | + |
| 172 | + def _get_mapped_field_value( |
| 173 | + self, field: dataclasses.Field, data: Dict[str, Any] |
| 174 | + ) -> Any: |
| 175 | + """ |
| 176 | + Handle the fact that Airtable omits fields for 'falsy' values. Use the field metadata to determine if we have |
| 177 | + a type supporting a 'falsy' value and return it if missing from the airtable response. |
| 178 | +
|
| 179 | + Args: |
| 180 | + field: Dataclass field descriptor for the resource field. |
| 181 | + data: The raw json object containing field values returned by Airtable. |
| 182 | +
|
| 183 | + Returns: |
| 184 | + The value in `data` identified by `field`, with the appropriate 'falsy' value substituted for missing values |
| 185 | + if relevant to the field type. |
| 186 | + """ |
| 187 | + |
| 188 | + mapped_name = self._get_mapped_field_name(field) |
| 189 | + if mapped_name in data: |
| 190 | + return data[mapped_name] |
| 191 | + |
| 192 | + type_info = get_type_info(field.type) |
| 193 | + |
| 194 | + if type_info.base_type == bool: |
| 195 | + return False |
| 196 | + |
| 197 | + if type_info.base_type == str: |
| 198 | + return "" |
| 199 | + |
| 200 | + if type_info.is_mapping: |
| 201 | + return {} |
| 202 | + |
| 203 | + if type_info.is_many: |
| 204 | + return [] |
| 205 | + |
| 206 | + return None |
0 commit comments