-
Notifications
You must be signed in to change notification settings - Fork 0
/
post_records.py
79 lines (64 loc) · 1.94 KB
/
post_records.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import os
import json
import urllib.parse
import urllib.request
from pathlib import Path
PRIMARY_KEYS = {
"albums": "id",
"artists": "id",
"history": "played_at",
"streaming_history": "played_at",
"tracks": "id",
}
# Following tutorial: https://www.datasette.cloud/blog/2023/datasette-cloud-api/
# Sending records
def fetch_records(filename: str | Path):
with open(filename, "r") as file:
records = json.load(file)
return records
def send_records(records, table, api_token):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_token}",
}
body = {
"table": table,
"rows": records,
"pk": PRIMARY_KEYS[table],
"ignore": True,
}
req = urllib.request.Request(
"https://esporifai.datasette.cloud/data/-/create",
data=json.dumps(body, default=str, ensure_ascii=False).encode("utf-8"),
headers=headers,
method="POST",
)
with urllib.request.urlopen(req) as response:
print(table, response.status, len(records))
def save_records(filename: str | Path, api_token):
if isinstance(filename, str):
filename = Path(filename)
table = filename.stem
batch = []
for record in fetch_records(filename):
batch.append(record)
if len(batch) == 100:
send_records(batch, table, api_token)
batch = []
if batch:
send_records(batch, table, api_token)
if __name__ == "__main__":
esporifai_token = os.environ.get("ESPORIFAI_DATASETTE_API_TOKEN")
if esporifai_token:
token = esporifai_token
else:
# If ESPORIFAI_DATASETTE_API_TOKEN is not set or empty, use DATASETTE_API_TOKEN
token = os.environ.get("DATASETTE_API_TOKEN")
for filename in [
"tracks.json",
"albums.json",
"artists.json",
"history.json",
"streaming_history.json",
]:
save_records(filename, token)