Created
December 19, 2023 10:04
-
-
Save anatolec/8d46dadc0abfbb601f478cc47ab711d9 to your computer and use it in GitHub Desktop.
A script to add a comment containing the Question ID on every Metabase question
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
METABASE_URL = '<YOUR_METABASE_URL>' | |
METABASE_USERNAME = '<YOUR_METABASE_USERNAME>' | |
METABASE_PASSWORD = '<YOUR_METABASE_PASSWORD>' | |
PREFIX = "-- METABASE_QUESTION_ID = " | |
SUFFIX = " - DO NOT CHANGE THIS LINE\n" | |
def login(): | |
response = requests.post( | |
f"{METABASE_URL}/api/session", | |
json={"username": METABASE_USERNAME, "password": METABASE_PASSWORD}, | |
).json() | |
global headers | |
headers = {"X-Metabase-Session": response["id"]} | |
def run(): | |
# Get all your Metabase questions | |
questions = requests.get(f"{METABASE_URL}/api/card", headers=headers).json() | |
for question in questions: | |
updated = False | |
native_query = question["dataset_query"]["native"]["query"] | |
id = question["id"] | |
prefix_place = native_query.find(PREFIX) | |
if prefix_place == -1: | |
# The prefix is not there, we add it | |
native_query = PREFIX + str(id) + SUFFIX + native_query | |
updated = True | |
else: | |
# The prefix is already there, we check whether the ID is correct (often users update questions and save them as new, so the comment is incorrect in that case) | |
old_id = int(re.findall(r'\d+', native_query[prefix_place: prefix_place + 35])[0]) | |
if old_id != id: | |
native_query = native_query.replace(f"{PREFIX}{old_id}", f"{PREFIX}{id}") | |
updated = True | |
if updated: | |
# Save the question if it was updated | |
question["dataset_query"]["native"]["query"] = native_query | |
requests.put(f"{METABASE_URL}/api/card/{id}", headers=headers, json=question) | |
if __name__ == '__main__': | |
login() | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment