Home > OS >  Grafana: How to use the selected range of time in a query?
Grafana: How to use the selected range of time in a query?

Time:07-15

I'm using Grafana with JSON API data source and I'd like to build a query that depends on the selected period of time selected in the upper right corner of the screen.

Is there any variable (or something like that), which I can send the selected time range form Grafana and receive it in my backend?

In other words, If I select 24hs in Grafana I'd like to use that in my query and return only data in this period.

I tried to get request from Grafana, which should contain the time range. However I got error: Failed to decode JSON object: Expecting value: line 1 column 1 (char 0).

It's possible that I misunderstood something and it doesn't work that way.

This is my /query endpoint:

@app.route('/query', methods=['POST', 'GET'])
def query():

    req = request.get_json()   <- failed
    range = req['request']['range']
    
    json_data = get_from_database(range)

    return json_data

Are there any other options, like sending the time range ( with these variables {__from}&to=${__to}) in URL?

CodePudding user response:

You can use the global variables $__from and $__to. As explained in the docs, ${__from} will give you Unix millisecond epoch, but there are also other format options.

How to use variables in the JSON API plugin is explained in the docs. So you can either use them as params what will result in a URL like this /query?range_start=${__from}&range_end=${__to} or use them directly in your path like this /query/${__from}/${__to}.

For retrieving them using python: you will find a lot on that topic on SO. Basically, I think you don't need .get_json() (will not work if the request is not application/json). If you send them as params, use request.args.get('range_start') to get the value (short explanation).

  • Related