Skip to Content

SQL and Python

Python guidelines

Rules for Python metrics: imports, filters, secrets and the result format.

Rules

Instructions popover listing the requests import, the client_id and metric_filters variables, and filter value types.
The editor's Instructions popover repeats these rules.
  • Assign a list of dictionaries to result. Each dictionary is one row, and each key is one column. Use the same keys in every row.
  • Return JSON values only: strings, numbers, booleans and None. Turn dates into strings.
  • You can import only requests, datetime and typing. Other imports are removed before the code runs.
  • exec, eval and open do nothing.
  • Give every requests call a timeout, and handle a failed response.

Filter by client

client_id is the viewer’s client ID. Your code must use it to fetch only that client’s rows. Databrain does not filter Python results for you.

Read filter values

metric_filters holds the metric’s Variable Filter values, keyed by filter name.

Filter typeValue
TextA string
NumberA number
DateA dictionary with start_date and end_date
region = metric_filters.get("region")
dates = metric_filters.get("order_date", {})
params = {"client": client_id, "region": region, "from": dates.get("start_date"), "to": dates.get("end_date")}
rows = requests.get(f"{secrets['secrets_BASE_URL']}/orders", params=params, timeout=10).json()
result = [{"day": r["day"], "orders": r["orders"]} for r in rows]

Use secrets

Read a secret by the name the Secrets page shows: a secret saved as BASE_URL is secrets['secrets_BASE_URL']. Never print a secret or put it in result. See Store secrets.

Caching

If the workspace has caching on, Databrain caches the result for the same code and client.

On this page