forked from KeithGalli/python-api-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbook.py
More file actions
52 lines (38 loc) · 1.5 KB
/
book.py
File metadata and controls
52 lines (38 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import os
from pyairtable import Api
from dotenv import load_dotenv
load_dotenv()
API_TOKEN = os.environ.get("API_TOKEN")
BASE_ID = os.environ.get("BASE_ID")
TABLE_ID = os.environ.get("TABLE_ID")
api = Api(API_TOKEN)
table = api.table(BASE_ID, TABLE_ID)
class BookReview:
def __init__(self):
self.api = Api(API_TOKEN)
self.table = self.api.table(BASE_ID, TABLE_ID)
def get_book_ratings(self, sort=None, max_records=10):
if not sort:
return self.table.all(max_records=max_records)
elif sort == "ASC":
rating = ["Rating"]
elif sort == "DESC":
rating = ["-Rating"]
table = self.table.all(sort=rating)[:max_records]
return table
def add_book_rating(self, book_title, rating, isbn, notes=None):
fields = {"Books": book_title, "Rating": rating, "Notes": notes, "ISBN": isbn}
self.table.create(fields=fields)
def update_book_rating(self, isbn, new_rating, new_notes=None):
# Fetch records filtered by ISBN
records = self.table.all(formula=f"{{ISBN}} = '{isbn}'")
if not records:
return None # No record found with the given ISBN
record_id = records[0]["id"]
updated_fields = {"Rating": new_rating}
if new_notes is not None:
updated_fields["Notes"] = new_notes
# Update the record using PATCH method
self.table.update(record_id, fields=updated_fields, typecast=True)
if __name__ == "__main__":
br = BookReview()