-
-
Save arikfr/e3e434d8cfd7f331d499ccf351abbff9 to your computer and use it in GitHub Desktop.
import os | |
import requests | |
import time | |
from pprint import pprint | |
def poll_job(s, redash_url, job): | |
# TODO: add timeout | |
while job['status'] not in (3,4): | |
response = s.get('{}/api/jobs/{}'.format(redash_url, job['id'])) | |
job = response.json()['job'] | |
time.sleep(1) | |
if job['status'] == 3: | |
return job['query_result_id'] | |
return None | |
def get_fresh_query_result(redash_url, query_id, api_key, parameters): | |
s = requests.Session() | |
s.headers.update({'Authorization': 'Key {}'.format(api_key)}) | |
body = { | |
"parameters": parameters | |
} | |
response = s.post('{}/api/queries/{}/results'.format(redash_url, query_id), json=body) | |
if response.status_code != 200: | |
raise Exception('Refresh failed.') | |
result_id = poll_job(s, redash_url, response.json()['job']) | |
if result_id: | |
response = s.get('{}/api/queries/{}/results/{}.json'.format(redash_url, query_id, result_id)) | |
if response.status_code != 200: | |
raise Exception('Failed getting results.') | |
else: | |
raise Exception('Query execution failed.') | |
return response.json()['query_result']['data']['rows'] | |
if __name__ == '__main__': | |
params = {'param': 1243} | |
query_id = 1234 | |
# Need to use a *user API key* here (and not a query API key). | |
api_key = '...' | |
pprint(get_fresh_query_result('https://app.redash.io/acme', query_id, api_key, params)) |
@susodapop my goal will be to work in ACME !!
Thank you ;)
Well this works just fine with 2 year old installation of redash, which is rather unexpected for some random gist on github.
Thanks!
@czen this "random gist on github" was written by the founder of Redash 😀
Nowadays you can also use redash-toolbelt to do this and many other operations as well. It's the officially maintained Redash API Python client.
i wonder, would there happen to be a way to have the query results stored as an excel file / csv / tsv instead of a json? would certainly make it easier for mass consumption.
i wonder, would there happen to be a way to have the query results stored as an excel file / csv / tsv instead of a json? would certainly make it easier for mass consumption.
CSV, TSV, and Excel versions of the results are already available through the API.
Are there any plans to add the ability to retrieve results from a parameterized query with a query api token instead of a user api token? My understanding is that currently this is not possible (as denoted by line 45 in the sample code above).
@aborruso The value
1243
is a query parameter. The value1234
is a query_id. These are just dummy numbers. If it helps,acme
isn't a real organization 😛. To run this script, you would replace them with real values. Also, you can add more than one parameter. It depends how many parameters your query requires.