Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass url parameters from dashboard to charts #8536

Merged
merged 7 commits into from
Nov 21, 2019
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions superset/assets/cypress/integration/dashboard/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import DashboardFilterTest from './filter';
import DashboardLoadTest from './load';
import DashboardSaveTest from './save';
import DashboardTabsTest from './tabs';
import DashboardUrlParamsTest from './url_params';

describe('Dashboard', () => {
DashboardControlsTest();
Expand All @@ -32,4 +33,5 @@ describe('Dashboard', () => {
DashboardLoadTest();
DashboardSaveTest();
DashboardTabsTest();
DashboardUrlParamsTest();
});
55 changes: 55 additions & 0 deletions superset/assets/cypress/integration/dashboard/url_params.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { WORLD_HEALTH_DASHBOARD } from './dashboard.helper';

export default () => describe('dashboard url params', () => {
let sliceIds = [];

beforeEach(() => {
cy.server();
cy.login();

cy.visit(WORLD_HEALTH_DASHBOARD + '?param1=123&param2=abc');
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here I would have used qs introduced in cypress 3.5.0 (https://docs.cypress.io/guides/references/changelog.html#3-5-0), but since we're still on 3.4.1, I had to put it in the URL by hand. If there are no objections, I can bump to 3.6.1 which would make this test slightly cleaner (being able to assert against the same object that's being passed to visit).

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


cy.get('#app').then((data) => {
const bootstrapData = JSON.parse(data[0].dataset.bootstrap);
const dashboard = bootstrapData.dashboard_data;
sliceIds = dashboard.slices.map(slice => (slice.slice_id));
});
});

it('should apply url params to slice requests', () => {
const aliases = [];
sliceIds
.forEach((id) => {
const alias = `getJson_${id}`;
aliases.push(`@${alias}`);
cy.route('POST', `/superset/explore_json/?form_data={"slice_id":${id}}`).as(alias);
});

cy.wait(aliases).then((requests) => {
requests.forEach((xhr) => {
const requestFormData = xhr.request.body;
const requestParams = JSON.parse(requestFormData.get('form_data'));
expect(requestParams.url_params)
.deep.eq({ param1: '123', param2: 'abc' });
});
});
});
});
13 changes: 10 additions & 3 deletions superset/assets/src/dashboard/reducers/getInitialState.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import newComponentFactory from '../util/newComponentFactory';
import { TIME_RANGE } from '../../visualizations/FilterBox/FilterBox';

export default function(bootstrapData) {
const { user_id, datasources, common, editMode } = bootstrapData;
const { user_id, datasources, common, editMode, urlParams } = bootstrapData;

const dashboard = { ...bootstrapData.dashboard_data };
let preselectFilters = {};
Expand Down Expand Up @@ -105,11 +105,18 @@ export default function(bootstrapData) {
dashboard.slices.forEach(slice => {
const key = slice.slice_id;
if (['separator', 'markup'].indexOf(slice.form_data.viz_type) === -1) {
const form_data = {
...slice.form_data,
url_params: {
...slice.form_data.url_params,
...urlParams,
},
};
chartQueries[key] = {
...chart,
id: key,
form_data: slice.form_data,
formData: applyDefaultFormData(slice.form_data),
form_data,
formData: applyDefaultFormData(form_data),
};

slices[key] = {
Expand Down
3 changes: 3 additions & 0 deletions superset/jinja_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ def url_param(param: str, default: Optional[str] = None) -> Optional[Any]:
parameters in the explore view as well as from the dashboard, and
it should carry through to your queries.

Default values for URL parameters can be defined in chart metdata by
adding the key-value pair `url_params: {'foo': 'bar'}`

:param param: the parameter to lookup
:param default: the value to return in the absence of the parameter
"""
Expand Down
14 changes: 11 additions & 3 deletions superset/utils/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
from email.utils import formatdate
from enum import Enum
from time import struct_time
from typing import Iterator, List, NamedTuple, Optional, Tuple, Union
from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Tuple, Union
from urllib.parse import unquote_plus

import bleach
Expand Down Expand Up @@ -933,8 +933,16 @@ def get_filter_key(f):
del form_data["extra_filters"]


def merge_request_params(form_data: dict, params: dict):
url_params = {}
def merge_request_params(form_data: Dict[str, Any], params: Dict[str, Any]) -> None:
"""
Merge request parameters to the key `url_params` in form_data. Only updates
or appends parameters to `form_data` that are defined in `params; pre-existing
parameters not defined in params are left unchanged.

:param form_data: object to be updated
:param params: request parameters received via query string
"""
url_params = form_data.get("url_params", {})
for key, value in params.items():
if key in ("form_data", "r"):
continue
Expand Down
6 changes: 6 additions & 0 deletions superset/views/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2192,13 +2192,19 @@ def dashboard(**kwargs):
"slice_can_edit": slice_can_edit,
}
)
url_params = {
key: value
for key, value in request.args.items()
if key not in ("edit", "standalone")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The blacklisting here seems brittle. Wondering if it's necessary.

}

bootstrap_data = {
"user_id": g.user.get_id(),
"dashboard_data": dashboard_data,
"datasources": {ds.uid: ds.data for ds in datasources},
"common": self.common_bootstrap_payload(),
"editMode": edit_mode,
"urlParams": url_params,
}

if request.args.get("json") == "true":
Expand Down
16 changes: 15 additions & 1 deletion tests/utils_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,14 +521,28 @@ def test_merge_extra_filters_adds_unequal_lists(self):
merge_extra_filters(form_data)
self.assertEqual(form_data, expected)

def test_merge_request_params(self):
def test_merge_request_params_when_url_params_undefined(self):
form_data = {"since": "2000", "until": "now"}
url_params = {"form_data": form_data, "dashboard_ids": "(1,2,3,4,5)"}
merge_request_params(form_data, url_params)
self.assertIn("url_params", form_data.keys())
self.assertIn("dashboard_ids", form_data["url_params"])
self.assertNotIn("form_data", form_data.keys())

def test_merge_request_params_when_url_params_predefined(self):
form_data = {
"since": "2000",
"until": "now",
"url_params": {"abc": "123", "dashboard_ids": "(1,2,3)"},
}
url_params = {"form_data": form_data, "dashboard_ids": "(1,2,3,4,5)"}
merge_request_params(form_data, url_params)
self.assertIn("url_params", form_data.keys())
self.assertIn("abc", form_data["url_params"])
self.assertEquals(
url_params["dashboard_ids"], form_data["url_params"]["dashboard_ids"]
)

def test_datetime_f(self):
self.assertEqual(
datetime_f(datetime(1990, 9, 21, 19, 11, 19, 626096)),
Expand Down