fastairtable 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastairtable/__init__.py +7 -0
- fastairtable/_modidx.py +50 -0
- fastairtable/core.py +308 -0
- fastairtable/formula.py +104 -0
- fastairtable/skill.py +36 -0
- fastairtable/spec.py +84 -0
- fastairtable-0.1.0.dist-info/METADATA +68 -0
- fastairtable-0.1.0.dist-info/RECORD +12 -0
- fastairtable-0.1.0.dist-info/WHEEL +5 -0
- fastairtable-0.1.0.dist-info/entry_points.txt +8 -0
- fastairtable-0.1.0.dist-info/licenses/LICENSE +202 -0
- fastairtable-0.1.0.dist-info/top_level.txt +1 -0
fastairtable/__init__.py
ADDED
fastairtable/_modidx.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# Autogenerated by octavo
|
|
2
|
+
|
|
3
|
+
d = { 'settings': { 'branch': 'main',
|
|
4
|
+
'lib_path': 'fastairtable',
|
|
5
|
+
'git_url': 'https://github.com/AnswerDotAI/fastairtable',
|
|
6
|
+
'doc_host': 'https://AnswerDotAI.github.io',
|
|
7
|
+
'doc_baseurl': '/fastairtable'},
|
|
8
|
+
'syms': { 'fastairtable.core': { 'fastairtable.core': ('api/core.html', 'fastairtable/core.py'),
|
|
9
|
+
'fastairtable.core.normalize_sort': ('api/core.html#normalize_sort', 'fastairtable/core.py'),
|
|
10
|
+
'fastairtable.core.unwrap_value': ('api/core.html#unwrap_value', 'fastairtable/core.py'),
|
|
11
|
+
'fastairtable.core.flatten_record': ('api/core.html#flatten_record', 'fastairtable/core.py'),
|
|
12
|
+
'fastairtable.core.Table': ('api/core.html#table', 'fastairtable/core.py'),
|
|
13
|
+
'fastairtable.core.Table.field_names': ('api/core.html#table.field_names', 'fastairtable/core.py'),
|
|
14
|
+
'fastairtable.core.Table.writable_fields': ( 'api/core.html#table.writable_fields',
|
|
15
|
+
'fastairtable/core.py'),
|
|
16
|
+
'fastairtable.core.Table.computed_fields': ( 'api/core.html#table.computed_fields',
|
|
17
|
+
'fastairtable/core.py'),
|
|
18
|
+
'fastairtable.core.Table.primary_field': ('api/core.html#table.primary_field', 'fastairtable/core.py'),
|
|
19
|
+
'fastairtable.core.Table.linked_tables': ('api/core.html#table.linked_tables', 'fastairtable/core.py'),
|
|
20
|
+
'fastairtable.core.Table.field': ('api/core.html#table.field', 'fastairtable/core.py'),
|
|
21
|
+
'fastairtable.core.Table.choices': ('api/core.html#table.choices', 'fastairtable/core.py'),
|
|
22
|
+
'fastairtable.core.Table.records': ('api/core.html#table.records', 'fastairtable/core.py'),
|
|
23
|
+
'fastairtable.core.Table.find': ('api/core.html#table.find', 'fastairtable/core.py'),
|
|
24
|
+
'fastairtable.core.Table.df': ('api/core.html#table.df', 'fastairtable/core.py'),
|
|
25
|
+
'fastairtable.core.Table.create': ('api/core.html#table.create', 'fastairtable/core.py'),
|
|
26
|
+
'fastairtable.core.Table.update': ('api/core.html#table.update', 'fastairtable/core.py'),
|
|
27
|
+
'fastairtable.core.Table.upsert': ('api/core.html#table.upsert', 'fastairtable/core.py'),
|
|
28
|
+
'fastairtable.core.Table.delete': ('api/core.html#table.delete', 'fastairtable/core.py'),
|
|
29
|
+
'fastairtable.core.Table.upload_attachment': ( 'api/core.html#table.upload_attachment',
|
|
30
|
+
'fastairtable/core.py'),
|
|
31
|
+
'fastairtable.core.Base': ('api/core.html#base', 'fastairtable/core.py'),
|
|
32
|
+
'fastairtable.core.Base.tables': ('api/core.html#base.tables', 'fastairtable/core.py'),
|
|
33
|
+
'fastairtable.core.Base.refresh': ('api/core.html#base.refresh', 'fastairtable/core.py'),
|
|
34
|
+
'fastairtable.core.Base.create_table': ('api/core.html#base.create_table', 'fastairtable/core.py'),
|
|
35
|
+
'fastairtable.core.AirtableClient': ('api/core.html#airtableclient', 'fastairtable/core.py'),
|
|
36
|
+
'fastairtable.core.AirtableClient.bases': ('api/core.html#airtableclient.bases', 'fastairtable/core.py'),
|
|
37
|
+
'fastairtable.core.AirtableClient.base': ('api/core.html#airtableclient.base', 'fastairtable/core.py'),
|
|
38
|
+
'fastairtable.core.airtable_client': ('api/core.html#airtable_client', 'fastairtable/core.py')},
|
|
39
|
+
'fastairtable.formula': { 'fastairtable.formula': ('api/formula.html', 'fastairtable/formula.py'),
|
|
40
|
+
'fastairtable.formula.Expr': ('api/formula.html#expr', 'fastairtable/formula.py'),
|
|
41
|
+
'fastairtable.formula.Expr.is_blank': ('api/formula.html#expr.is_blank', 'fastairtable/formula.py'),
|
|
42
|
+
'fastairtable.formula.Expr.contains': ('api/formula.html#expr.contains', 'fastairtable/formula.py'),
|
|
43
|
+
'fastairtable.formula.Expr.in_': ('api/formula.html#expr.in_', 'fastairtable/formula.py'),
|
|
44
|
+
'fastairtable.formula.Expr.or_else': ('api/formula.html#expr.or_else', 'fastairtable/formula.py'),
|
|
45
|
+
'fastairtable.formula.F': ('api/formula.html#f', 'fastairtable/formula.py'),
|
|
46
|
+
'fastairtable.formula.where_formula': ('api/formula.html#where_formula', 'fastairtable/formula.py'),
|
|
47
|
+
'fastairtable.formula.combine_formulas': ( 'api/formula.html#combine_formulas',
|
|
48
|
+
'fastairtable/formula.py')},
|
|
49
|
+
'fastairtable.spec': { 'fastairtable.spec': ('api/spec.html', 'fastairtable/spec.py'),
|
|
50
|
+
'fastairtable.spec.airtable_spec': ('api/spec.html#airtable_spec', 'fastairtable/spec.py')}}}
|
fastairtable/core.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"Schema-aware async Python client for Airtable built on `fastspec`."
|
|
2
|
+
# - order: 1
|
|
3
|
+
# - title: Core API
|
|
4
|
+
|
|
5
|
+
import base64, mimetypes
|
|
6
|
+
from collections.abc import Iterable, Mapping
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
from fastcore.meta import delegates
|
|
10
|
+
from fastcore.utils import *
|
|
11
|
+
from fastspec.oapi import OpenAPIClient
|
|
12
|
+
from pyskills import allow
|
|
13
|
+
|
|
14
|
+
from .formula import Expr, combine_formulas
|
|
15
|
+
from .spec import BASE_URL, CONTENT_URL, airtable_spec
|
|
16
|
+
|
|
17
|
+
__all__ = ['AirtableClient', 'Base', 'Table', 'airtable_client', 'normalize_sort', 'unwrap_value', 'flatten_record']
|
|
18
|
+
|
|
19
|
+
_BATCH_SIZE = 10
|
|
20
|
+
_COMPUTED_TYPES = {'formula', 'rollup', 'count', 'multipleLookupValues', 'lookup',
|
|
21
|
+
'createdTime', 'lastModifiedTime', 'createdBy', 'lastModifiedBy', 'autoNumber', 'button', 'aiText'}
|
|
22
|
+
_LOOKUP_TYPES = {'multipleLookupValues', 'lookup', 'rollup', 'formula'}
|
|
23
|
+
|
|
24
|
+
def _as_payload(rows): return [r if set(r) == {'fields'} else {'fields': dict(r)} for r in listify(rows)]
|
|
25
|
+
def _md_cell(s) -> str: return ' '.join(str(s).split()).replace('|', r'\|')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def normalize_sort(sort: str | Iterable[str | Mapping] | None) -> list[dict] | None:
|
|
29
|
+
"Convert shorthand sort specs such as `['Name', '-Date']` to Airtable `sort` dicts."
|
|
30
|
+
if not sort: return None
|
|
31
|
+
return [dict(o) if isinstance(o, Mapping) else
|
|
32
|
+
({'field': o[1:], 'direction': 'desc'} if o.startswith('-') else {'field': o, 'direction': 'asc'}) for o in listify(sort)]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def unwrap_value(val, field_type: str = None, mode: Literal['single', 'strict', 'all', False] = 'single', field_name: str = ''):
|
|
36
|
+
"Unwrap 1-element lookup arrays to scalars while preserving multi-element lists."
|
|
37
|
+
if not isinstance(val, (list, L)): return val
|
|
38
|
+
if not mode or (mode != 'all' and field_type is not None and field_type not in _LOOKUP_TYPES): return list(val)
|
|
39
|
+
if not val: return None
|
|
40
|
+
if len(val) == 1: return val[0]
|
|
41
|
+
if mode == 'strict':
|
|
42
|
+
lbl = f' for field {field_name!r}' if field_name else ''
|
|
43
|
+
raise ValueError(f'Expected at most 1 value{lbl}, got {len(val)}: {val!r}')
|
|
44
|
+
return list(val)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def flatten_record(rec: Mapping, cols: Iterable[str] = None, field_types: Mapping[str, str] = None,
|
|
48
|
+
unwrap: Literal['single', 'strict', 'all', False] = 'single', resolved: Mapping[str, dict] = None) -> AttrDict:
|
|
49
|
+
"Flatten an Airtable record envelope into an `AttrDict` with `None`-filled blank fields."
|
|
50
|
+
flds, ftypes = rec.get('fields') or {}, field_types or {}
|
|
51
|
+
out = AttrDict()
|
|
52
|
+
for k in dict.fromkeys([*(cols or ()), *flds]):
|
|
53
|
+
v = flds.get(k)
|
|
54
|
+
if resolved and k in resolved and isinstance(v, (list, L)): v = [resolved[k].get(x, x) for x in v]
|
|
55
|
+
out[f'{k}_' if k in ('id', 'createdTime') else k] = unwrap_value(v, ftypes.get(k), mode=unwrap, field_name=k)
|
|
56
|
+
out['id'] = rec['id']
|
|
57
|
+
if 'createdTime' in rec: out['createdTime'] = rec['createdTime']
|
|
58
|
+
return out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Table:
|
|
62
|
+
"Schema-aware Airtable table bound to an immutable `tbl...` ID."
|
|
63
|
+
def __init__(self, base: 'Base', schema: Mapping):
|
|
64
|
+
self.base, self.schema = base, dict2obj(schema)
|
|
65
|
+
self.id, self.name, self.fields = self.schema.id, self.schema.name, L(self.schema.get('fields') or [])
|
|
66
|
+
self._by_name, self._by_id = {f.name: f for f in self.fields}, {f.id: f for f in self.fields}
|
|
67
|
+
self._ftypes = {f.name: f.type for f in self.fields}
|
|
68
|
+
|
|
69
|
+
def __repr__(self) -> str: return f'Table({self.name!r}, id={self.id!r}, fields={len(self.fields)})'
|
|
70
|
+
@property
|
|
71
|
+
def field_names(self) -> L: return self.fields.attrgot('name')
|
|
72
|
+
@property
|
|
73
|
+
def writable_fields(self) -> L: return self.fields.filter(lambda f: f.type not in _COMPUTED_TYPES).attrgot('name')
|
|
74
|
+
@property
|
|
75
|
+
def computed_fields(self) -> L: return self.fields.filter(lambda f: f.type in _COMPUTED_TYPES).attrgot('name')
|
|
76
|
+
@property
|
|
77
|
+
def primary_field(self) -> str:
|
|
78
|
+
pf = self._by_id.get(self.schema.get('primaryFieldId')) or first(self.fields)
|
|
79
|
+
return pf.name if pf else ''
|
|
80
|
+
@property
|
|
81
|
+
def linked_tables(self) -> dict[str, str]:
|
|
82
|
+
return {f.name: tid for f in self.fields
|
|
83
|
+
if f.type == 'multipleRecordLinks' and (tid := nested_idx(f, 'options', 'linkedTableId'))}
|
|
84
|
+
|
|
85
|
+
def field(self, name_or_id: str) -> AttrDict:
|
|
86
|
+
"Return field schema by exact field name or `fld...` ID."
|
|
87
|
+
f = self._by_name.get(name_or_id) or self._by_id.get(name_or_id)
|
|
88
|
+
if f is None: raise KeyError(f'Unknown field {name_or_id!r} in {self.name!r}. Available: {list(self.field_names)}')
|
|
89
|
+
return f
|
|
90
|
+
|
|
91
|
+
def choices(self, field_name: str) -> L:
|
|
92
|
+
"Return valid option names for a `singleSelect` or `multipleSelects` field."
|
|
93
|
+
return L(nested_idx(self.field(field_name), 'options', 'choices') or []).itemgot('name')
|
|
94
|
+
|
|
95
|
+
def _repr_markdown_(self) -> str:
|
|
96
|
+
rows = [f'### `{self.name}` (`{self.id}`)', '', '| Field | Type | Access | Details |', '|---|---|---|---|']
|
|
97
|
+
for f in self.fields:
|
|
98
|
+
acc, opts = ('computed' if f.type in _COMPUTED_TYPES else 'writable'), (f.get('options') or {})
|
|
99
|
+
if ch := opts.get('choices'): det = ', '.join(L(ch[:6]).itemgot('name')) + (f' … (+{len(ch) - 6} more)' if len(ch) > 6 else '')
|
|
100
|
+
elif tid := opts.get('linkedTableId'):
|
|
101
|
+
lt = self.base._by_id.get(tid)
|
|
102
|
+
det = f'→ `{lt.name}`' if lt else f'`{tid}`'
|
|
103
|
+
else: det = f.get('description') or ''
|
|
104
|
+
rows.append(f'| `{_md_cell(f.name)}` | `{f.type}` | {acc} | {_md_cell(det)} |')
|
|
105
|
+
return '\n'.join(rows)
|
|
106
|
+
|
|
107
|
+
def _col_key(self, f: str, by_id: bool = False) -> str:
|
|
108
|
+
fld = self._by_id.get(f) or self._by_name.get(f)
|
|
109
|
+
return (fld.id if by_id else fld.name) if fld else f
|
|
110
|
+
|
|
111
|
+
async def _resolve_links(self, raw_recs: list, cols: list[str], by_id: bool = False) -> dict[str, dict]:
|
|
112
|
+
links = {self._col_key(k, by_id): tid for k, tid in self.linked_tables.items() if self._col_key(k, by_id) in cols}
|
|
113
|
+
if not links: return {}
|
|
114
|
+
ids_by_tbl = {}
|
|
115
|
+
for rec in raw_recs:
|
|
116
|
+
for col, tid in links.items():
|
|
117
|
+
vals = nested_idx(rec, 'fields', col)
|
|
118
|
+
if isinstance(vals, (list, L)): ids_by_tbl.setdefault(tid, set()).update(v for v in vals if isinstance(v, str))
|
|
119
|
+
fetched = {}
|
|
120
|
+
for tid, rids in ids_by_tbl.items():
|
|
121
|
+
if not rids or tid not in self.base._by_id: continue
|
|
122
|
+
lt = self.base._by_id[tid]
|
|
123
|
+
pf, rmap = lt.primary_field, {}
|
|
124
|
+
for grp in chunked(sorted(rids), 50):
|
|
125
|
+
fml = 'OR(' + ', '.join(f"RECORD_ID()='{rid}'" for rid in grp) + ')'
|
|
126
|
+
for r in await lt.records(fields=[pf], formula=fml, raw=True): rmap[r['id']] = (r.get('fields') or {}).get(pf, r['id'])
|
|
127
|
+
fetched[tid] = rmap
|
|
128
|
+
return {col: fetched.get(tid, {}) for col, tid in links.items()}
|
|
129
|
+
|
|
130
|
+
async def records(
|
|
131
|
+
self,
|
|
132
|
+
fields: str | Iterable[str] = None, # Field name(s) (or `fld...` IDs, translated to names unless `returnFieldsByFieldId=True`)
|
|
133
|
+
where: str | Expr | Mapping = None, # Dict filter (`field__op`) or `Expr`
|
|
134
|
+
formula: str | Expr = None, # Additional Airtable formula combined via `AND`
|
|
135
|
+
sort: str | Iterable[str | Mapping] = None, # Field names (prefix `-` for desc) or Airtable sort dicts
|
|
136
|
+
view: str = None, # Airtable view name or ID
|
|
137
|
+
max_records: int = None, # Maximum total records to fetch across pages
|
|
138
|
+
page_size: int = 100, # Records per page (1-100)
|
|
139
|
+
unwrap: Literal['single', 'strict', 'all', False] = 'single', # Lookup unwrap mode ('single', 'strict', 'all', or False)
|
|
140
|
+
resolve_links: bool = False, # Batch-resolve linked `rec...` IDs to primary field values
|
|
141
|
+
raw: bool = False, # Return raw Airtable record dicts
|
|
142
|
+
**kwargs,
|
|
143
|
+
) -> L:
|
|
144
|
+
"Fetch all matching records across pages as flat `AttrDict` rows."
|
|
145
|
+
fcols = None if fields is None else listify(fields)
|
|
146
|
+
body = {k: v for k, v in dict(fields=fcols, filterByFormula=combine_formulas(where, formula) or None,
|
|
147
|
+
maxRecords=max_records, pageSize=page_size, sort=normalize_sort(sort), view=view, **kwargs).items() if v is not None}
|
|
148
|
+
raw_recs, offset = [], None
|
|
149
|
+
while True:
|
|
150
|
+
if offset: body['offset'] = offset
|
|
151
|
+
resp = await self.base.cli.records.list(self.base.id, self.id, **body)
|
|
152
|
+
raw_recs.extend(resp.get('records') or [])
|
|
153
|
+
offset = resp.get('offset')
|
|
154
|
+
if not offset or (max_records is not None and len(raw_recs) >= max_records): break
|
|
155
|
+
if max_records is not None: raw_recs = raw_recs[:max_records]
|
|
156
|
+
if raw: return L(raw_recs)
|
|
157
|
+
by_id = bool(kwargs.get('returnFieldsByFieldId'))
|
|
158
|
+
cols = [self._col_key(f, by_id) for f in fcols] if fcols is not None else (list(self.fields.attrgot('id')) if by_id else list(self.field_names))
|
|
159
|
+
ftypes = {f.id: f.type for f in self.fields} if by_id else self._ftypes
|
|
160
|
+
resolved = await self._resolve_links(raw_recs, cols, by_id) if resolve_links else None
|
|
161
|
+
return L(flatten_record(r, cols, ftypes, unwrap, resolved) for r in raw_recs)
|
|
162
|
+
|
|
163
|
+
async def find(self, where=None, formula=None, fields=None, unwrap='single', resolve_links=False, **eq) -> AttrDict | None:
|
|
164
|
+
"Return the first matching flat record, or `None` when no record matches."
|
|
165
|
+
return first(await self.records(fields=fields, formula=combine_formulas(where, eq or None, formula),
|
|
166
|
+
max_records=1, page_size=1, unwrap=unwrap, resolve_links=resolve_links))
|
|
167
|
+
|
|
168
|
+
@delegates(records, but=['raw'])
|
|
169
|
+
async def df(self, fields=None, index: str = None, include_id: bool = True, **kwargs):
|
|
170
|
+
"Fetch records into a `pandas.DataFrame` with guaranteed columns even when empty."
|
|
171
|
+
if 'raw' in kwargs: raise TypeError('df() does not support raw=True; use records(raw=True)')
|
|
172
|
+
import pandas as pd
|
|
173
|
+
by_id = bool(kwargs.get('returnFieldsByFieldId'))
|
|
174
|
+
fcols = (list(self.fields.attrgot('id')) if by_id else list(self.field_names)) if fields is None else [self._col_key(f, by_id) for f in listify(fields)]
|
|
175
|
+
rows = await self.records(fields=fields, **kwargs)
|
|
176
|
+
dcols = [f'{c}_' if c in ('id', 'createdTime') else c for c in fcols]
|
|
177
|
+
cols = (['id'] + dcols) if include_id else dcols
|
|
178
|
+
df = pd.DataFrame([{c: r.get(c) for c in cols} for r in rows], columns=cols)
|
|
179
|
+
return df.set_index(index) if index else df
|
|
180
|
+
|
|
181
|
+
def _flat(self, recs: list) -> L: return L(flatten_record(r, list(self.field_names), self._ftypes) for r in recs)
|
|
182
|
+
|
|
183
|
+
async def _batch(self, op, payload: list[dict], **kw) -> L:
|
|
184
|
+
out = []
|
|
185
|
+
for grp in chunked(payload, _BATCH_SIZE): out.extend((await op(self.base.id, self.id, records=grp, **kw)).get('records') or [])
|
|
186
|
+
return self._flat(out)
|
|
187
|
+
|
|
188
|
+
async def create(self, rows: Mapping | Iterable[Mapping], *, typecast: bool = False):
|
|
189
|
+
"Create one record (dict) or many records (iterable of dicts), auto-chunked by 10."
|
|
190
|
+
single = isinstance(rows, Mapping)
|
|
191
|
+
res = await self._batch(self.base.cli.records.create, _as_payload(rows), typecast=typecast)
|
|
192
|
+
return res[0] if single else res
|
|
193
|
+
|
|
194
|
+
async def update(self, record_id_or_rows: str | Mapping | Iterable[Mapping], fields: Mapping = None, *, replace: bool = False, typecast: bool = False):
|
|
195
|
+
"Update one record (by ID or row dict) or a batch of records (auto-chunked by 10)."
|
|
196
|
+
if isinstance(record_id_or_rows, str):
|
|
197
|
+
op = self.base.cli.records.replace if replace else self.base.cli.records.update
|
|
198
|
+
return self._flat([await op(self.base.id, self.id, record_id_or_rows, fields=dict(fields or {}), typecast=typecast)])[0]
|
|
199
|
+
single = isinstance(record_id_or_rows, Mapping)
|
|
200
|
+
op = self.base.cli.records.batch_replace if replace else self.base.cli.records.batch_update
|
|
201
|
+
payload = [dict(r) if 'fields' in r and set(r) <= {'id', 'fields'} else
|
|
202
|
+
{'id': r['id'], 'fields': {k: v for k, v in r.items() if k not in ('id', 'createdTime')}} for r in listify(record_id_or_rows)]
|
|
203
|
+
res = await self._batch(op, payload, typecast=typecast)
|
|
204
|
+
return res[0] if single else res
|
|
205
|
+
|
|
206
|
+
async def upsert(self, rows: Mapping | Iterable[Mapping], key: str | Iterable[str], *, replace: bool = False, typecast: bool = False):
|
|
207
|
+
"Insert or update records by 1-3 writable natural key(s) (`performUpsert.fieldsToMergeOn`), auto-chunked by 10."
|
|
208
|
+
single, keys = isinstance(rows, Mapping), listify(key)
|
|
209
|
+
op = self.base.cli.records.batch_replace if replace else self.base.cli.records.batch_update
|
|
210
|
+
res = await self._batch(op, _as_payload(rows), performUpsert={'fieldsToMergeOn': keys}, typecast=typecast)
|
|
211
|
+
return res[0] if single else res
|
|
212
|
+
|
|
213
|
+
async def delete(self, record_ids: str | Iterable[str]) -> L:
|
|
214
|
+
"Delete one record ID or a list of record IDs (auto-chunked by 10)."
|
|
215
|
+
deleted = L()
|
|
216
|
+
for grp in chunked(listify(record_ids), _BATCH_SIZE):
|
|
217
|
+
resp = await self.base.cli.records.batch_delete(self.base.id, self.id, records=grp)
|
|
218
|
+
deleted.extend(r['id'] for r in (resp.get('records') or []) if r.get('deleted', True))
|
|
219
|
+
return deleted
|
|
220
|
+
|
|
221
|
+
async def upload_attachment(self, record_id: str, field: str, content: bytes | Path, filename: str = None, content_type: str = None):
|
|
222
|
+
"Upload a file (<= 5 MB) to an attachment field via `content.airtable.com`."
|
|
223
|
+
if isinstance(content, Path): filename, content = filename or content.name, content.read_bytes()
|
|
224
|
+
if not filename: raise ValueError('filename is required when content is bytes')
|
|
225
|
+
ctype = content_type or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
|
226
|
+
url = f'{CONTENT_URL}/v0/{self.base.id}/{record_id}/{self.field(field).id}/uploadAttachment'
|
|
227
|
+
body = dict(contentType=ctype, filename=filename, file=base64.b64encode(content).decode('ascii'))
|
|
228
|
+
return dict2obj(await self.base.cli.transport.request('POST', url, json=body))
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class Base:
|
|
232
|
+
"Schema-aware Airtable base caching `/v0/meta/bases/{baseId}/tables`."
|
|
233
|
+
def __init__(self, cli: 'AirtableClient', base_id: str, tables_schema: list, name: str = None):
|
|
234
|
+
self.cli, self.id, self.name = cli, base_id, name or base_id
|
|
235
|
+
self._load(tables_schema)
|
|
236
|
+
|
|
237
|
+
def _load(self, tables_schema: list):
|
|
238
|
+
self.schema = L(dict2obj(t) for t in tables_schema)
|
|
239
|
+
self._tables = L(Table(self, t) for t in self.schema)
|
|
240
|
+
self._by_name, self._by_id = {t.name: t for t in self._tables}, {t.id: t for t in self._tables}
|
|
241
|
+
|
|
242
|
+
@property
|
|
243
|
+
def tables(self) -> L: return self._tables.attrgot('name')
|
|
244
|
+
def __repr__(self) -> str: return f'Base({self.name!r}, id={self.id!r}, tables={list(self.tables)})'
|
|
245
|
+
|
|
246
|
+
def __getitem__(self, name_or_id: str) -> Table:
|
|
247
|
+
t = self._by_name.get(name_or_id) or self._by_id.get(name_or_id)
|
|
248
|
+
if t is None: raise KeyError(f'Unknown table {name_or_id!r} in {self.name!r}. Available: {list(self.tables)}')
|
|
249
|
+
return t
|
|
250
|
+
|
|
251
|
+
def _repr_markdown_(self) -> str:
|
|
252
|
+
rows = [f'### Base `{self.name}` (`{self.id}`)', '', '| Table | ID | Fields |', '|---|---|---:|']
|
|
253
|
+
rows.extend(f'| `{t.name}` | `{t.id}` | {len(t.fields)} |' for t in self._tables)
|
|
254
|
+
return '\n'.join(rows)
|
|
255
|
+
|
|
256
|
+
async def refresh(self) -> 'Base':
|
|
257
|
+
"Reload cached table and field schemas from Airtable."
|
|
258
|
+
self._load((await self.cli.meta.list_tables(self.id)).get('tables') or [])
|
|
259
|
+
return self
|
|
260
|
+
|
|
261
|
+
async def create_table(self, name: str, fields: list[dict], description: str = None) -> Table:
|
|
262
|
+
"Create a table in this base, refresh cached schemas, and return the new `Table`."
|
|
263
|
+
kw = merge(dict(name=name, fields=fields), {'description': description} if description is not None else {})
|
|
264
|
+
created = await self.cli.meta.create_table(self.id, **kw)
|
|
265
|
+
await self.refresh()
|
|
266
|
+
return self[created['id']]
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class AirtableClient(OpenAPIClient):
|
|
270
|
+
"Airtable `OpenAPIClient` with schema-aware `bases()` and `base(name_or_id)` helpers."
|
|
271
|
+
async def bases(self) -> L:
|
|
272
|
+
"List all bases accessible to this token across pages."
|
|
273
|
+
res, offset = L(), None
|
|
274
|
+
while True:
|
|
275
|
+
resp = await self.meta.list_bases(**({'offset': offset} if offset else {}))
|
|
276
|
+
res.extend(resp.get('bases') or [])
|
|
277
|
+
if not (offset := resp.get('offset')): break
|
|
278
|
+
return res
|
|
279
|
+
|
|
280
|
+
async def base(self, name_or_id: str = None) -> Base:
|
|
281
|
+
"Open a `Base` by human name or `app...` ID (defaults to `AIRTABLE_BASE_ID`)."
|
|
282
|
+
target = ifnone(name_or_id, os.getenv('AIRTABLE_BASE_ID'))
|
|
283
|
+
if not target: raise ValueError('Pass a base name/ID or set AIRTABLE_BASE_ID')
|
|
284
|
+
bid, bname = (target, None) if target.startswith('app') and len(target) >= 10 else (None, None)
|
|
285
|
+
if not bid:
|
|
286
|
+
blist = await self.bases()
|
|
287
|
+
matches = blist.filter(lambda b: b.name == target)
|
|
288
|
+
if not matches: raise KeyError(f'Unknown base {target!r}. Available: {list(blist.attrgot("name"))}')
|
|
289
|
+
if len(matches) > 1: raise ValueError(f'Multiple bases named {target!r}: {list(matches.attrgot("id"))}')
|
|
290
|
+
bid, bname = matches[0].id, matches[0].name
|
|
291
|
+
return Base(self, bid, (await self.meta.list_tables(bid)).get('tables') or [], name=bname)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
@allow
|
|
295
|
+
@delegates(OpenAPIClient)
|
|
296
|
+
def airtable_client(
|
|
297
|
+
api_key: str = None, # Airtable Personal Access Token; defaults to `AIRTABLE_API_KEY`
|
|
298
|
+
*, base_url: str = BASE_URL, # Airtable REST API host
|
|
299
|
+
headers: dict = None, # Extra HTTP headers merged into every request
|
|
300
|
+
**kwargs,
|
|
301
|
+
) -> AirtableClient:
|
|
302
|
+
"Create an `AirtableClient` covering Airtable's Web API and schema-aware `Base`/`Table` helpers."
|
|
303
|
+
key = ifnone(api_key, os.getenv('AIRTABLE_API_KEY'))
|
|
304
|
+
hdrs = dict(headers or {})
|
|
305
|
+
if key: hdrs.setdefault('Authorization', f'Bearer {key}')
|
|
306
|
+
cli = AirtableClient(airtable_spec(), base_url=base_url, headers=hdrs, **kwargs)
|
|
307
|
+
allow(cli)
|
|
308
|
+
return cli
|
fastairtable/formula.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"Composable Airtable formula expressions (`F`) and dictionary filters (`where_formula`)."
|
|
2
|
+
# - order: 2
|
|
3
|
+
# - title: Formulas
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from datetime import date, datetime, timezone
|
|
7
|
+
import operator as _op
|
|
8
|
+
|
|
9
|
+
__all__ = ['Expr', 'F', 'where_formula', 'combine_formulas']
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _escape_field(name: str) -> str:
|
|
13
|
+
esc = str(name).replace('\\', '\\\\').replace('}', r'\}')
|
|
14
|
+
return '{' + esc + '}'
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _lit(val) -> str:
|
|
18
|
+
if isinstance(val, Expr): return str(val)
|
|
19
|
+
if val is None: return 'BLANK()'
|
|
20
|
+
if isinstance(val, bool): return 'TRUE()' if val else 'FALSE()'
|
|
21
|
+
if isinstance(val, (int, float)): return str(val)
|
|
22
|
+
if isinstance(val, datetime):
|
|
23
|
+
s = val.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z' if val.tzinfo else val.isoformat()
|
|
24
|
+
return f"DATETIME_PARSE('{s}')"
|
|
25
|
+
if isinstance(val, date): return f"DATETIME_PARSE('{val.isoformat()}')"
|
|
26
|
+
s = str(val).replace('\\', '\\\\').replace("'", r"\'").replace('\n', r'\n').replace('\r', r'\r').replace('\t', r'\t')
|
|
27
|
+
return f"'{s}'"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _join(fn: str, parts: list[str]) -> str:
|
|
31
|
+
parts = [p for p in parts if p]
|
|
32
|
+
if not parts: return ''
|
|
33
|
+
return parts[0] if len(parts) == 1 else f"{fn}({', '.join(parts)})"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Expr:
|
|
37
|
+
"Composable Airtable formula expression supporting `&`, `|`, `~`, and comparison operators."
|
|
38
|
+
def __init__(self, src: str): self.src = src
|
|
39
|
+
def __str__(self) -> str: return self.src
|
|
40
|
+
def __repr__(self) -> str: return f'Expr({self.src!r})'
|
|
41
|
+
def __bool__(self): raise TypeError('Use &, |, ~ to combine Expr, not and/or/not or chained comparisons')
|
|
42
|
+
|
|
43
|
+
def __eq__(self, other) -> 'Expr': return Expr(f'{self.src}={_lit(other)}')
|
|
44
|
+
def __ne__(self, other) -> 'Expr': return Expr(f'{self.src}!={_lit(other)}')
|
|
45
|
+
def __lt__(self, other) -> 'Expr': return Expr(f'{self.src}<{_lit(other)}')
|
|
46
|
+
def __le__(self, other) -> 'Expr': return Expr(f'{self.src}<={_lit(other)}')
|
|
47
|
+
def __gt__(self, other) -> 'Expr': return Expr(f'{self.src}>{_lit(other)}')
|
|
48
|
+
def __ge__(self, other) -> 'Expr': return Expr(f'{self.src}>={_lit(other)}')
|
|
49
|
+
|
|
50
|
+
def __and__(self, other) -> 'Expr': return Expr(f'AND({self.src}, {other})')
|
|
51
|
+
def __or__(self, other) -> 'Expr': return Expr(f'OR({self.src}, {other})')
|
|
52
|
+
def __invert__(self) -> 'Expr': return Expr(f'NOT({self.src})')
|
|
53
|
+
|
|
54
|
+
def is_blank(self) -> 'Expr':
|
|
55
|
+
"True when the field is genuinely empty (`({f}&'')=''`, differing from Airtable's `{f}=BLANK()`, which also matches numeric `0`)."
|
|
56
|
+
return Expr(f"({self.src}&'')=''")
|
|
57
|
+
|
|
58
|
+
def contains(self, sub: str, *, case: bool = True) -> 'Expr':
|
|
59
|
+
"True when `sub` appears inside the field's text value."
|
|
60
|
+
if case: return Expr(f'FIND({_lit(sub)}, {self.src})>0')
|
|
61
|
+
return Expr(f'FIND(LOWER({_lit(sub)}), LOWER({self.src}))>0')
|
|
62
|
+
|
|
63
|
+
def in_(self, values) -> 'Expr':
|
|
64
|
+
"True when the field equals any item in `values`."
|
|
65
|
+
vals = list(values)
|
|
66
|
+
if not vals: return Expr('FALSE()')
|
|
67
|
+
return Expr(_join('OR', [f'{self.src}={_lit(v)}' for v in vals]))
|
|
68
|
+
|
|
69
|
+
def or_else(self, fallback) -> 'Expr':
|
|
70
|
+
"Return this value when truthy, otherwise `fallback` (`IF(a, a, fallback)`)."
|
|
71
|
+
fb = _lit(fallback)
|
|
72
|
+
return Expr(f'IF({self.src}, {self.src}, {fb})')
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def F(name: str) -> Expr:
|
|
76
|
+
"Reference an Airtable field (escaping spaces and punctuation)."
|
|
77
|
+
return Expr(_escape_field(name))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
_OP_FNS = {'eq': _op.eq, 'ne': _op.ne, 'lt': _op.lt, 'lte': _op.le, 'gt': _op.gt, 'gte': _op.ge, 'in': Expr.in_,
|
|
81
|
+
'contains': Expr.contains, 'icontains': lambda f, v: f.contains(v, case=False), 'blank': lambda f, v: f.is_blank() if v else ~f.is_blank()}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def where_formula(where: str | Expr | Mapping | None) -> str:
|
|
85
|
+
"""Compile `where` into an Airtable `filterByFormula` string.
|
|
86
|
+
|
|
87
|
+
Dict keys accept `__op` suffixes (`eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in`, `contains`, `icontains`, `blank`); unknown `__` suffixes stay part of the field name. `__blank` emits `({field}&'')=''` rather than Airtable's `{field}=BLANK()` so numeric `0` is not treated as blank.
|
|
88
|
+
"""
|
|
89
|
+
if where is None: return ''
|
|
90
|
+
if isinstance(where, (str, Expr)): return str(where)
|
|
91
|
+
if not where: return ''
|
|
92
|
+
parts = []
|
|
93
|
+
for k, v in where.items():
|
|
94
|
+
fld, op = k, 'eq'
|
|
95
|
+
if '__' in k:
|
|
96
|
+
head, tail = k.rsplit('__', 1)
|
|
97
|
+
if tail in _OP_FNS: fld, op = head, tail
|
|
98
|
+
parts.append(str(_OP_FNS[op](F(fld), v)))
|
|
99
|
+
return _join('AND', parts)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def combine_formulas(*parts) -> str:
|
|
103
|
+
"Combine non-empty formula strings, `Expr`s, or `where` dicts with `AND(...)`."
|
|
104
|
+
return _join('AND', [where_formula(p) for p in parts if p is not None])
|
fastairtable/skill.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
r"""Read, query, inspect schemas, and update Airtable bases, tables, records, comments, and webhooks from Python instead of hand-built HTTP calls or `pyairtable`.
|
|
2
|
+
|
|
3
|
+
### Workflow
|
|
4
|
+
|
|
5
|
+
- `at = airtable_client()` (`AIRTABLE_API_KEY`); `base = await at.base('My Base')` (or `await at.base()` via `AIRTABLE_BASE_ID`) resolves base name to `app...` and caches table/field schemas
|
|
6
|
+
- inspect before querying or writing: display `base` or `base['Table']` for types, writable vs computed flags, select choices, and linked tables (`tbl.fields` to search wide tables, `tbl.choices`, `tbl.writable_fields`, `tbl.computed_fields`); `await base.refresh()` reloads after schema edits
|
|
7
|
+
- `base['Table']` (or `base['tbl...']`) binds to the immutable `tbl...` ID for `records`, `find`, `df`, `create`, `update`, `upsert`, `delete`, and `upload_attachment`
|
|
8
|
+
- filtering: `where=dict(field__op=val)` (`doc(where_formula)`), `F('Field')` expressions (`&`, `|`, `~`, `.or_else()`, `.contains()`, `.in_()`, `.is_blank()`), or raw `formula=...`; `where=` and `formula=` combine via `AND`; `date`/`datetime` values compile to `DATETIME_PARSE` in UTC (use half-open `__gte=start, __lt=next_day` on `dateTime`/`createdTime` fields so same-day timestamps are not missed)
|
|
9
|
+
- raw `fastspec` endpoints (`at.meta`, `at.records`, `at.comments`, `at.webhooks`) live on the client instance: inspect live with `doc(at.records)` / `doc(at.records.list)`
|
|
10
|
+
|
|
11
|
+
### Lookup unwrapping (`unwrap=` on `records`/`df`)
|
|
12
|
+
|
|
13
|
+
Mode|Behavior
|
|
14
|
+
-|-
|
|
15
|
+
`'single'` (default)|unwraps 1-element lookup/rollup/formula lists to scalars; keeps `multipleSelects`, `multipleAttachments`, `multipleRecordLinks`, and >1 values as lists (columns with both single and multi links mix scalars and lists)
|
|
16
|
+
`'strict'`|same as `'single'`, but raises `ValueError` if a lookup/rollup/formula field has >1 value
|
|
17
|
+
`'all'`|unwraps any 1-element list regardless of field type
|
|
18
|
+
`False`|returns raw lists unchanged
|
|
19
|
+
|
|
20
|
+
### Gotchas
|
|
21
|
+
|
|
22
|
+
- `records()` auto-pages `POST .../listRecords` and fills omitted blank Airtable fields as `None`; `fields=` takes field names primarily (`fld...` IDs translate to names unless `returnFieldsByFieldId=True`); `df()` preserves columns on empty results (optional `pandas` dep)
|
|
23
|
+
- Airtable formula functions on blank fields evaluate to `#ERROR` and drop rows from enclosing `OR(...)` clauses unless guarded with `IF({f}, ...)`
|
|
24
|
+
- `is_blank()` and `__blank` compile to `({field}&'')=''` instead of Airtable's standard `{field}=BLANK()` so numeric `0` is not matched as blank
|
|
25
|
+
- user fields named `id` or `createdTime` flatten to `id_` / `createdTime_` so `row.id` always stays the Airtable `rec...` ID
|
|
26
|
+
- `upsert(rows, key=...)` updates by natural key (`performUpsert.fieldsToMergeOn`, 1–3 writable fields) without fetching `rec...` IDs; writes fail if `tbl.computed_fields` are included
|
|
27
|
+
- `create`, `update`, `upsert`, `delete` accept one item or an iterable and auto-chunk to Airtable's 10-record cap; `upload_attachment` caps at 5 MB (`content.airtable.com`)
|
|
28
|
+
- `resolve_links=True` batch-replaces linked `rec...` IDs with linked primary-field values
|
|
29
|
+
- Airtable caps requests at 5 req/s per base (30s HTTP 429 lockout); pass custom `transport=` when pacing or 429 retry is needed
|
|
30
|
+
- `sync=True` makes raw REST ops blocking while `Base`/`Table` helpers stay async
|
|
31
|
+
- Airtable's API cannot delete bases, tables, or fields—only records; confirm before mutating live data
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from . import AirtableClient, Base, Expr, F, Table, airtable_client, combine_formulas, where_formula
|
|
35
|
+
|
|
36
|
+
__all__ = ['airtable_client', 'AirtableClient', 'Base', 'Table', 'F', 'Expr', 'where_formula', 'combine_formulas']
|
fastairtable/spec.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Compact `fastspec` specification for Airtable's fixed Web API endpoints."""
|
|
2
|
+
# - order: 3
|
|
3
|
+
# - title: Spec
|
|
4
|
+
|
|
5
|
+
from fastspec.spec import OpSpec, SpecParser
|
|
6
|
+
|
|
7
|
+
__all__ = ['BASE_URL', 'CONTENT_URL', 'airtable_spec']
|
|
8
|
+
|
|
9
|
+
BASE_URL, CONTENT_URL = 'https://api.airtable.com', 'https://content.airtable.com'
|
|
10
|
+
|
|
11
|
+
_LIST_PARAMS = dict(
|
|
12
|
+
fields=(list, 'Field names or IDs to include'), filterByFormula=(str, 'Airtable formula filtering records'),
|
|
13
|
+
maxRecords=(int, 'Max total records'), pageSize=(int, 'Records per page (1-100)'),
|
|
14
|
+
sort=(list, 'List of {"field", "direction"} dicts'), view=(str, 'View name or ID'),
|
|
15
|
+
cellFormat=(str, '"json" or "string"'), timeZone=(str, 'IANA timezone'), userLocale=(str, 'Locale string'),
|
|
16
|
+
returnFieldsByFieldId=(bool, 'Key fields by fld... ID'), offset=(str, 'Pagination cursor'),
|
|
17
|
+
recordMetadata=(list, 'Extra metadata, e.g. ["commentCount"]'),
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _op(group, name, verb, path, summary, route=(), query=None, body=None, req=()):
|
|
22
|
+
q, b = query or {}, body or {}
|
|
23
|
+
ptypes = {p: str for p in route} | {k: t for src in (q, b) for k, (t, _) in src.items()}
|
|
24
|
+
pdocs = {k: d for src in (q, b) for k, (_, d) in src.items()}
|
|
25
|
+
return OpSpec(group=group, name=name, path=path, verb=verb, summary=summary,
|
|
26
|
+
route_params=list(route), query_params=list(q), body_params=list(b),
|
|
27
|
+
required_params=list(dict.fromkeys([*route, *req])), param_types=ptypes, param_docs=pdocs)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def airtable_spec() -> SpecParser:
|
|
31
|
+
"Return a `SpecParser` covering Airtable's Web, Metadata, Comments, and Webhooks APIs."
|
|
32
|
+
rt, rr = ('base_id', 'table_id'), ('base_id', 'table_id', 'record_id')
|
|
33
|
+
ret_id = dict(returnFieldsByFieldId=(bool, 'Key returned fields by fld... ID'))
|
|
34
|
+
wopt = dict(typecast=(bool, 'Auto-convert values to field types'), **ret_id)
|
|
35
|
+
rbody = dict(records=(list, 'Up to 10 {"id"?, "fields": {...}} dicts'),
|
|
36
|
+
performUpsert=(dict, '{"fieldsToMergeOn": [field, ...]}'), **wopt)
|
|
37
|
+
gopt = dict(cellFormat=(str, '"json" or "string"'), timeZone=(str, 'IANA timezone'), userLocale=(str, 'Locale'), **ret_id)
|
|
38
|
+
ops = [
|
|
39
|
+
_op('meta', 'whoami', 'GET', '/v0/meta/whoami', 'Authenticated user ID and scopes'),
|
|
40
|
+
_op('meta', 'list_bases', 'GET', '/v0/meta/bases', 'List accessible bases', query=dict(offset=(str, 'Cursor'))),
|
|
41
|
+
_op('meta', 'create_base', 'POST', '/v0/meta/bases', 'Create a base in a workspace',
|
|
42
|
+
body=dict(name=(str, 'Base name'), workspaceId=(str, 'Workspace ID'), tables=(list, 'Initial tables')),
|
|
43
|
+
req=('name', 'workspaceId', 'tables')),
|
|
44
|
+
_op('meta', 'list_tables', 'GET', '/v0/meta/bases/{base_id}/tables', 'List table schemas in a base',
|
|
45
|
+
('base_id',), query=dict(include=(list, 'Extra metadata, e.g. ["visibleFieldIds"]'))),
|
|
46
|
+
_op('meta', 'create_table', 'POST', '/v0/meta/bases/{base_id}/tables', 'Create a table in a base', ('base_id',),
|
|
47
|
+
body=dict(name=(str, 'Table name'), fields=(list, 'Field definitions'), description=(str, 'Description')),
|
|
48
|
+
req=('name', 'fields')),
|
|
49
|
+
_op('meta', 'update_table', 'PATCH', '/v0/meta/bases/{base_id}/tables/{table_id}', 'Update table metadata', rt,
|
|
50
|
+
body=dict(name=(str, 'New name'), description=(str, 'New description'))),
|
|
51
|
+
_op('meta', 'create_field', 'POST', '/v0/meta/bases/{base_id}/tables/{table_id}/fields', 'Add a field to a table', rt,
|
|
52
|
+
body=dict(name=(str, 'Field name'), type=(str, 'Field type'), options=(dict, 'Field options'), description=(str, 'Description')),
|
|
53
|
+
req=('name', 'type')),
|
|
54
|
+
_op('meta', 'update_field', 'PATCH', '/v0/meta/bases/{base_id}/tables/{table_id}/fields/{field_id}', 'Update field metadata',
|
|
55
|
+
(*rt, 'field_id'), body=dict(name=(str, 'New name'), description=(str, 'New description'))),
|
|
56
|
+
_op('records', 'list', 'POST', '/v0/{base_id}/{table_id}/listRecords', 'List records via JSON body', rt, body=_LIST_PARAMS),
|
|
57
|
+
_op('records', 'get', 'GET', '/v0/{base_id}/{table_id}/{record_id}', 'Fetch one record by ID', rr, query=gopt),
|
|
58
|
+
_op('records', 'create', 'POST', '/v0/{base_id}/{table_id}', 'Create 1 (`fields`) or up to 10 (`records`) records', rt,
|
|
59
|
+
body=dict(records=(list, 'Up to 10 {"fields": {...}} dicts'), fields=(dict, 'Single record fields'), **wopt)),
|
|
60
|
+
_op('records', 'update', 'PATCH', '/v0/{base_id}/{table_id}/{record_id}', 'Partially update one record', rr,
|
|
61
|
+
body=dict(fields=(dict, 'Fields to update'), **wopt), req=('fields',)),
|
|
62
|
+
_op('records', 'replace', 'PUT', '/v0/{base_id}/{table_id}/{record_id}', 'Replace writable fields on one record', rr,
|
|
63
|
+
body=dict(fields=(dict, 'Complete fields dict'), **wopt), req=('fields',)),
|
|
64
|
+
_op('records', 'batch_update', 'PATCH', '/v0/{base_id}/{table_id}', 'Update or upsert up to 10 records', rt, body=rbody, req=('records',)),
|
|
65
|
+
_op('records', 'batch_replace', 'PUT', '/v0/{base_id}/{table_id}', 'Replace or upsert up to 10 records', rt, body=rbody, req=('records',)),
|
|
66
|
+
_op('records', 'delete', 'DELETE', '/v0/{base_id}/{table_id}/{record_id}', 'Delete one record', rr),
|
|
67
|
+
_op('records', 'batch_delete', 'DELETE', '/v0/{base_id}/{table_id}', 'Delete up to 10 records by ID', rt,
|
|
68
|
+
query={'records[]': (list, 'Up to 10 rec... IDs')}, req=('records[]',)),
|
|
69
|
+
_op('comments', 'list', 'GET', '/v0/{base_id}/{table_id}/{record_id}/comments', 'List record comments', rr,
|
|
70
|
+
query=dict(pageSize=(int, 'Page size'), offset=(str, 'Cursor'))),
|
|
71
|
+
_op('comments', 'create', 'POST', '/v0/{base_id}/{table_id}/{record_id}/comments', 'Create a record comment', rr,
|
|
72
|
+
body=dict(text=(str, 'Comment text'), parentCommentId=(str, 'Parent comment ID')), req=('text',)),
|
|
73
|
+
_op('comments', 'update', 'PATCH', '/v0/{base_id}/{table_id}/{record_id}/comments/{comment_id}', 'Edit a comment',
|
|
74
|
+
(*rr, 'comment_id'), body=dict(text=(str, 'Updated text')), req=('text',)),
|
|
75
|
+
_op('comments', 'delete', 'DELETE', '/v0/{base_id}/{table_id}/{record_id}/comments/{comment_id}', 'Delete a comment', (*rr, 'comment_id')),
|
|
76
|
+
_op('webhooks', 'list', 'GET', '/v0/bases/{base_id}/webhooks', 'List base webhooks', ('base_id',)),
|
|
77
|
+
_op('webhooks', 'create', 'POST', '/v0/bases/{base_id}/webhooks', 'Create a base webhook', ('base_id',),
|
|
78
|
+
body=dict(notificationUrl=(str, 'Callback URL'), specification=(dict, 'Webhook spec')), req=('specification',)),
|
|
79
|
+
_op('webhooks', 'delete', 'DELETE', '/v0/bases/{base_id}/webhooks/{webhook_id}', 'Delete a webhook', ('base_id', 'webhook_id')),
|
|
80
|
+
_op('webhooks', 'refresh', 'POST', '/v0/bases/{base_id}/webhooks/{webhook_id}/refresh', 'Refresh webhook expiry', ('base_id', 'webhook_id')),
|
|
81
|
+
_op('webhooks', 'payloads', 'GET', '/v0/bases/{base_id}/webhooks/{webhook_id}/payloads', 'List webhook payloads',
|
|
82
|
+
('base_id', 'webhook_id'), query=dict(cursor=(int, 'Payload cursor'), limit=(int, 'Max payloads'))),
|
|
83
|
+
]
|
|
84
|
+
return SpecParser(BASE_URL, ops)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastairtable
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Schema-aware Airtable client and PySkill built on fastspec
|
|
5
|
+
Author-email: Nathan Cooper <nathanacooper@proton.me>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/AnswerDotAI/fastairtable
|
|
8
|
+
Project-URL: Documentation, https://AnswerDotAI.github.io/fastairtable/
|
|
9
|
+
Project-URL: Repository, https://github.com/AnswerDotAI/fastairtable
|
|
10
|
+
Project-URL: Issues, https://github.com/AnswerDotAI/fastairtable/issues
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Requires-Python: >=3.11
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: fastcore>=2.2.23
|
|
17
|
+
Requires-Dist: fastspec>=0.2.8
|
|
18
|
+
Requires-Dist: fasttransport>=0.0.2
|
|
19
|
+
Requires-Dist: pyskills>=0.0.30
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: fastship[all]; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# fastairtable
|
|
25
|
+
|
|
26
|
+
Schema-aware async Python client and PySkill for Airtable built on [`fastspec`](https://github.com/AnswerDotAI/fastspec).
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
pip install fastairtable
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick Start
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from datetime import date
|
|
38
|
+
from fastairtable import airtable_client, F
|
|
39
|
+
|
|
40
|
+
at = airtable_client() # reads AIRTABLE_API_KEY
|
|
41
|
+
base = await at.base("My Base") # or await at.base() using AIRTABLE_BASE_ID
|
|
42
|
+
|
|
43
|
+
# Inspect tables, fields, and select choices
|
|
44
|
+
base.tables
|
|
45
|
+
base["Clients"].choices("Plan")
|
|
46
|
+
|
|
47
|
+
# Query flat records with safe lookup unwrapping and Pythonic filters
|
|
48
|
+
projects = await base["Projects"].records(
|
|
49
|
+
where=dict(
|
|
50
|
+
created_at__gte=date(2026, 10, 1),
|
|
51
|
+
category="Fixed",
|
|
52
|
+
status__ne="Canceled",
|
|
53
|
+
),
|
|
54
|
+
sort=["-created_at"],
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Load a DataFrame with guaranteed columns even when empty
|
|
58
|
+
clients = await base["Clients"].df(
|
|
59
|
+
fields=["name", "Plan", "external_id"],
|
|
60
|
+
index="name",
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# Upsert by natural key without fetching rec... IDs first
|
|
64
|
+
await base["Clients"].upsert(
|
|
65
|
+
{"name": "Acme Corp", "external_id": "ext_123"},
|
|
66
|
+
key="name",
|
|
67
|
+
)
|
|
68
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
fastairtable/__init__.py,sha256=_aInb4R9-sVlXe7yLbt2XN3RQjK7F9Jv8W6hAgZmfmg,168
|
|
2
|
+
fastairtable/_modidx.py,sha256=dGoZr6CRRSR7xv4Mom9S592X_pxPl7SGKWdoeYxbmBg,5611
|
|
3
|
+
fastairtable/core.py,sha256=liRMmSKFdLB5TDlGO1Cpf6slEJDOLplEz988jkKL7kA,17948
|
|
4
|
+
fastairtable/formula.py,sha256=zduu7aNOVeZujTMarosvDiHim7i52qTRWI1m3UeRMuw,4676
|
|
5
|
+
fastairtable/skill.py,sha256=EAeGyYB1VyV-lV_QgEq9thsfvXyHpXiSaMbMGeeQgwI,3614
|
|
6
|
+
fastairtable/spec.py,sha256=5EQfSAeS2qiSctbRE7m5d5u5TgOl9OMKijrPTijl4aU,7036
|
|
7
|
+
fastairtable-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
8
|
+
fastairtable-0.1.0.dist-info/METADATA,sha256=Zi7Sa8EsYuTLS_0GB6-dxGhdb-W1T80Qth2s_Ascnrw,2006
|
|
9
|
+
fastairtable-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
fastairtable-0.1.0.dist-info/entry_points.txt,sha256=mdp0SHga2H9Ytw6GyVM7CCzZOq1GtuQPeaFyp5njF3M,146
|
|
11
|
+
fastairtable-0.1.0.dist-info/top_level.txt,sha256=iHKs6f6iw5tzkXXh9BfKzSNRD4uYPP0ApQAf_ZmxSRY,13
|
|
12
|
+
fastairtable-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fastairtable
|