Repository navigation
Expand file tree
/
Copy pathscript.py
More file actions
143 lines (120 loc) · 4.2 KB
/
Copy pathscript.py
File metadata and controls
143 lines (120 loc) · 4.2 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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import requests
# --- CONFIGURATION ---
METABASE_HOST = "http://localhost:3000"
USERNAME = "arshad@shikshalokam.org"
PASSWORD = "Shaikh@313"
COLLECTION_NAME = "A4 Collection"
QUESTION_NAME = "Dev Projects Table"
# SQL_QUERY = "SELECT * FROM dev_projects WHERE 1=1 AND state_name = {{state_name}}"
SQL_QUERY = """SELECT
*
FROM
dev_projects
WHERE 1=1
[[AND {{state_name}}]];
"""
DASHBOARD_NAME = "A4 Dashboard"
def get_session_token():
res = requests.post(
f"{METABASE_HOST}/api/session",
json={"username": USERNAME, "password": PASSWORD}
)
res.raise_for_status()
data = res.json()
if not isinstance(data, dict) or "id" not in data:
raise ValueError(f"[ERROR] Unexpected response: {data}")
token = str(data["id"])
print(f"[1] Session Token: {token}")
return token
def get_database_id_by_name(token, db_name):
print("inside get_database_id_by_name")
headers = {"X-Metabase-Session": token}
res = requests.get(f"{METABASE_HOST}/api/database", headers=headers)
res.raise_for_status()
databases = res.json().get("data", [])
for db in databases:
if db["name"] == db_name:
print(f"[2] Found DB '{db_name}' with ID: {db['id']}")
return db["id"]
raise ValueError(f"Database '{db_name}' not found.")
def create_collection(token):
headers = {"X-Metabase-Session": token}
res = requests.post(
f"{METABASE_HOST}/api/collection",
json={"name": COLLECTION_NAME},
headers=headers
)
res.raise_for_status()
collection_id = res.json()["id"]
print(f"[3] Collection ID: {collection_id}")
return collection_id
def create_question(token, collection_id, db_id):
headers = {"X-Metabase-Session": token}
payload = {
"name": QUESTION_NAME,
"dataset_query": {
"type": "native",
"native": {"query": SQL_QUERY},
"database": db_id,
"parameters": [
{
#"id": "77ce5c53-d414-432f-bfa0-ef83fe4d1981",
"type": "location",
"target": ["variable", ["template-tag", "state_name"]],
"name": "State Name",
"slug": "state_name",
}
]
},
"display": "table",
"visualization_settings": {},
"collection_id": collection_id
}
#print(payload)
res = requests.post(f"{METABASE_HOST}/api/card", json=payload, headers=headers)
res.raise_for_status()
card_id = res.json()["id"]
print(f"[4] Question (Card) ID: {card_id}")
return card_id
def create_dashboard(token, collection_id):
headers = {"X-Metabase-Session": token}
payload = {
"name": DASHBOARD_NAME,
"collection_id": collection_id
}
res = requests.post(f"{METABASE_HOST}/api/dashboard", json=payload, headers=headers)
res.raise_for_status()
dashboard_id = res.json()["id"]
print(f"[5] Dashboard ID: {dashboard_id}")
return dashboard_id
def add_card_to_dashboard(token, dashboard_id, card_id):
headers = {"X-Metabase-Session": token}
payload = {
"cardId": card_id,
"sizeX": 4,
"sizeY": 4,
"row": 0,
"col": 0
}
res = requests.put(
f"{METABASE_HOST}/api/dashboard/{dashboard_id}",
json=payload,
headers=headers
)
res.raise_for_status()
print(f"[6] Card {card_id} added to Dashboard {dashboard_id}")
def main():
try:
token = get_session_token()
db_id = get_database_id_by_name(token, "Projects")
collection_id = create_collection(token)
card_id = create_question(token, collection_id, db_id)
dashboard_id = create_dashboard(token, collection_id)
add_card_to_dashboard(token, dashboard_id, card_id)
print("\n All steps completed successfully!")
except requests.exceptions.HTTPError as http_err:
print(f"[HTTP ERROR] {http_err.response.status_code} - {http_err.response.text}")
except Exception as e:
print(f"[ERROR] {str(e)}")
if __name__ == "__main__":
main()