### Query Export Example Setup Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Sets up the Redash client and retrieves all paginated queries. This is a prerequisite for using the `save_queries` function to export them. ```python from redash_toolbelt.examples.query_export import save_queries from redash_toolbelt import Redash client = Redash(url, key) queries = client.paginate(client.queries) ``` -------------------------------- ### Install Redash Toolbelt from Source Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md Follow these steps to clone the repository and install the Redash Toolbelt in editable mode. ```bash git clone https://github.com/getredash/redash-toolbelt.git cd redash-toolbelt pip install -e . ``` -------------------------------- ### Install redash-toolbelt Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/README.md Install the redash-toolbelt library using pip. ```bash pip install redash-toolbelt ``` -------------------------------- ### Build and Install Local Package Source: https://github.com/getredash/redash-toolbelt/blob/master/redash_toolbelt/docs/redash-migrate/README.md Build the redash-toolbelt package using Poetry and install the generated .tar.gz archive using pip for local testing. ```shell # Build the package with Poetry. This will create a .tar.gz file in the /dist directory poetry build # Use to pip to install the .tar.gz archive created in the previous step pip install dist/redash_toolbelt-x.x.x.tar.gz ``` -------------------------------- ### Clone and Set Up Development Environment Source: https://github.com/getredash/redash-toolbelt/blob/master/redash_toolbelt/docs/redash-migrate/README.md Clone the repository, create and activate a Python virtual environment, and install Poetry for package management. ```shell # Clone redash-toolbelt to your disk git clone https://github.com/getredash/redash-toolbelt.git # Create a Python virtual environment using version 3.6+ python3 -m virtualenv ${env_name} # Activate your virtual environment . ${env_name}/bin/activate # macOS ${env_name}\scripts\activate # Windows # We use Poetry to build redash-toolbelt for distribution on PyPi pip install poetry ``` -------------------------------- ### Example Metafile Structure Source: https://github.com/getredash/redash-toolbelt/blob/master/redash_toolbelt/docs/redash-migrate/README.md This JSON snippet shows an example of the meta.json file, illustrating how origin query IDs are mapped to destination query IDs. ```json // example meta.json "queries": { "108171": 6, "219541": 7, "381761": 8 }, ``` -------------------------------- ### Redash Client Example Usage Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Demonstrates basic usage of the Redash client, including fetching paginated queries and retrieving a specific dashboard. ```python from redash_toolbelt import Redash client = Redash('https://app.redash.io/acme', 'my_api_key') queries = client.paginate(client.queries) dashboard = client.dashboard('my-dashboard') ``` -------------------------------- ### Example: Query Export Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md CLI tool and function to export Redash queries to a file. ```APIDOC ## Example: Query Export ### Description This example provides a command-line tool and a Python function to export all Redash queries to a local file. ### CLI `export-queries URL [--api-key KEY]` ### Main Function `save_queries(queries: list[dict]) -> None`: Saves a list of query dictionaries to a file. ``` -------------------------------- ### Initialize Redash Migration Source: https://github.com/getredash/redash-toolbelt/blob/master/redash_toolbelt/docs/redash-migrate/README.md Run this command before starting the migration process. It creates the meta.json file and prompts for authentication details. ```bash redash-migrate init ``` -------------------------------- ### Install Redash Toolbelt Source: https://github.com/getredash/redash-toolbelt/blob/master/README.md Install or upgrade the redash-toolbelt package using pip. Ensure you have Python 3.6 or above. ```bash pip install --upgrade redash-toolbelt ``` -------------------------------- ### Verify redash-migrate Installation Source: https://github.com/getredash/redash-toolbelt/blob/master/redash_toolbelt/docs/redash-migrate/README.md Checks if the redash-migrate command is installed and accessible by displaying its version. This command is available after installing redash-toolbelt. ```bash redash-migrate --version ``` -------------------------------- ### Initialize Redash Migration Tool Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/05-migrate-tool.md Use the `init` command to start an interactive prompt for creating a new `meta.json` file. This process collects necessary connection details for both origin and destination Redash instances. ```bash $ redash-migrate init [Logo displayed] Thank you for using redash-migrate... Please enter the origin URL. Example: https://app.redash.io/acme: https://app.redash.io/company Please enter an admin API key for the origin instance: secret_key_1234 Please enter the integer user id for this admin on the origin instance: 1 Please enter the destination URL. Example: http://localhost: http://localhost:5000 Please enter an admin API key for the destination instance: dest_key_5678 Please enter the integer user id for this admin on the destination instance: 1 Please enter the email address for the destination admin user: admin@localhost Ready to proceed. ``` -------------------------------- ### GDPR Scrub Example Initialization Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Initializes the GDPR scrubbing utility by creating a Redash client and a Lookup object with a list of emails to search for. Requires Redash client and Lookup class. ```python from redash_toolbelt.examples.gdpr_scrub import Lookup from redash_toolbelt import Redash client = Redash(url, key) lookup = Lookup(client, ['email@example.com']) ``` -------------------------------- ### Example: Clone Dashboard and Queries Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md CLI tool and function to duplicate a Redash dashboard along with its associated queries. ```APIDOC ## Example: Clone Dashboard and Queries ### Description This example provides a command-line tool and a Python function to duplicate an existing Redash dashboard and all its queries, optionally adding a prefix to the new dashboard's name. ### CLI `clone-dashboard-and-queries URL SLUG PREFIX [--api-key KEY]` ### Main Function `duplicate(client: Redash, slug: str, prefix: str = None) -> dict`: Duplicates a dashboard identified by its slug and returns the new dashboard object. ``` -------------------------------- ### Clone Dashboard and Queries Example Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Initializes the Redash client and calls the `duplicate` function to clone a dashboard. The `prefix` argument is optional for naming the new dashboard. ```python from redash_toolbelt.examples.clone_dashboard_and_queries import duplicate from redash_toolbelt import Redash client = Redash(url, key) new_dash = duplicate(client, 'original-slug', prefix='COPY_') ``` -------------------------------- ### Import Redash and get_frontend_vals Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/API-EXPORTS.md Import the main Redash client class and the utility function for getting frontend values. ```python from redash_toolbelt import Redash, get_frontend_vals ``` -------------------------------- ### Example: Find Table Names in Queries Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md CLI tool and functions to extract and analyze table names used in Redash queries. ```APIDOC ## Example: Find Table Names ### Description This example provides a command-line interface and Python functions to scan Redash queries and identify the tables they reference. ### CLI `find-tables URL KEY DATA_SOURCE_ID [--detail]` ### Key Functions - `extract_table_names(str_sql) -> list[str]`: Parses table names from a SQL string. - `find_table_names(url, key, data_source_id) -> dict`: Scans all queries for a given data source. - `format_query(str_sql) -> str`: Normalizes SQL syntax. - `print_summary(dict)`: Prints a summary of table usage. - `print_details(dict)`: Prints detailed query-to-table mappings. ``` -------------------------------- ### Use Date Ranges in Parameterized Queries Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/03-date-ranges.md Example of how to use the get_frontend_vals function to retrieve date ranges and format them for use in a Redash parameterized query. Requires Redash client setup. ```python from redash_toolbelt import Redash, get_frontend_vals client = Redash('https://app.redash.io/acme', 'my_api_key') dates = get_frontend_vals() # Use in parameterized query params = { 'start_date': dates.d_last_30_days.start.strftime('%Y-%m-%d'), 'end_date': dates.d_last_30_days.end.strftime('%Y-%m-%d') } client._post('api/queries/123/results', json={ 'parameters': params, 'max_age': 0 }) ``` -------------------------------- ### Example: Refresh Dashboard Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md CLI tool and function to refresh all queries associated with a given Redash dashboard. ```APIDOC ## Example: Refresh Dashboard ### Description This example provides a command-line tool and a Python function to trigger a refresh for all queries belonging to a specified Redash dashboard. ### CLI `refresh-dashboard URL KEY SLUG` ### Key Functions - `refresh_dashboard(url, key, slug) -> None`: Refreshes all queries on the dashboard identified by its slug. - `get_queries_on_dashboard(client, slug) -> dict`: Retrieves the queries associated with a dashboard. - `fill_dynamic_val(dates, param)`: A helper function to fill dynamic date parameters. ``` -------------------------------- ### Redash Toolbelt CLI Commands Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/README.md Examples of using various command-line interface tools provided by redash-toolbelt for common Redash management tasks. ```bash # Analyze tables in queries find-tables https://app.redash.io/acme data_source_id # Export all queries to .sql files export-queries https://app.redash.io/acme --api-key api_key # Search for email addresses (GDPR) gdpr-scrub https://app.redash.io/acme user@example.com # Clone a dashboard clone-dashboard-and-queries https://app.redash.io/acme dashboard_slug PREFIX # Migrate between instances (15 commands) redash-migrate init redash-migrate data-sources redash-migrate users # ... etc ``` -------------------------------- ### Troubleshooting Redash Toolbelt Installation Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Provides solutions for common Redash Toolbelt issues, such as missing imports or meta.json configuration errors. Recommends upgrading the package or re-running migration commands. ```text Missing import | Old version installed | pip install --upgrade redash-toolbelt meta.json errors | Configuration issue | Run redash-migrate init again ``` -------------------------------- ### Check Installed Redash Toolbelt Version Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md Verify the installed version of the redash-toolbelt package using pip or by importing the package directly in Python. ```bash pip show redash-toolbelt # or python -c "import redash_toolbelt; print(redash_toolbelt.__version__)" ``` -------------------------------- ### Execute a Specific Query with Parameters Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md Use this snippet for minimal setup to execute a specific Redash query with dynamic parameters. Ensure you have your Redash URL and API key. ```python from redash_toolbelt import Redash # Minimal setup client = Redash('https://app.redash.io/acme', 'api_key') # Execute query client._post('api/queries/123/results', json={ 'parameters': {'date': '2026-07-01'}, 'max_age': 0 }) ``` -------------------------------- ### SQL: Define a parameterized query in Redash Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/03-date-ranges.md Example of a Redash SQL query with dynamic date parameters `start_date` and `end_date` that can be filled by the redash-toolbelt. ```sql SELECT revenue FROM sales WHERE sale_date BETWEEN {{ start_date }} AND {{ end_date }} ``` -------------------------------- ### Duplicate a Dashboard and its Queries Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md Use this example to duplicate an existing Redash dashboard along with its associated queries. Requires the 'clone_dashboard_and_queries' module. ```python from redash_toolbelt import Redash from redash_toolbelt.examples.clone_dashboard_and_queries import duplicate client = Redash(url, key) new_dashboard = duplicate(client, 'original-slug', new_name='Dashboard Copy') ``` -------------------------------- ### Example: Refresh Query Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Function to execute a specific Redash query and retrieve its latest results, with optional parameters. ```APIDOC ## Example: Refresh Query ### Description This function executes a specified Redash query and returns its most recent results. It allows for passing query parameters to customize the execution. ### Key Functions - `get_fresh_query_result(url, query_id, api_key, params) -> list[dict]`: Executes a query by its ID and returns the results. `params` is a dictionary of query parameters. - `poll_job(session, url, job) -> int|None`: Polls the Redash API to check the status of a query job. ``` -------------------------------- ### Example: GDPR Scrub Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md CLI tool and class to help identify and potentially scrub sensitive data (like emails) from Redash queries and dashboards. ```APIDOC ## Example: GDPR Scrub ### Description This example provides a command-line tool and a Python class to assist with GDPR compliance by searching for specific data (e.g., email addresses) within Redash queries and dashboards. ### CLI `gdpr-scrub URL EMAIL [EMAIL ...] [--api-key KEY]` ### Main Class `Lookup` ### Key Methods - `check_query(query) -> bool`: Checks if a query contains the specified data. - `check_dashboard(dashboard) -> bool`: Checks if a dashboard contains the specified data. - `lookup()`: Scans all queries and dashboards and prints URLs containing the specified data. ``` -------------------------------- ### Refresh Query Example Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Executes a specific Redash query with optional parameters and retrieves its latest results. Requires Redash URL, query ID, API key, and a dictionary of parameters. ```python from redash_toolbelt.examples.refresh_query import get_fresh_query_result rows = get_fresh_query_result( 'https://app.redash.io/acme', query_id=123, api_key='my_key', params={'date': '2026-07-01'} ) ``` -------------------------------- ### Refresh Dashboard Example Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Initiates a refresh for all queries associated with a given Redash dashboard. Requires Redash URL, API key, and the dashboard's slug. ```python from redash_toolbelt.examples.refresh_dashboard import refresh_dashboard refresh_dashboard('https://app.redash.io/acme', 'my_key', 'dashboard-slug') ``` -------------------------------- ### Perform GDPR Search for User Data Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md This example uses the 'Lookup' class from 'gdpr_scrub' to search for a user's data across Redash queries and dashboards. It requires the user's email address. ```python from redash_toolbelt import Redash from redash_toolbelt.examples.gdpr_scrub import Lookup client = Redash(url, key) search = Lookup(client, ['user@example.com']) search.lookup() # Prints URLs of matching queries and dashboards ``` -------------------------------- ### Find Table Names Example Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Imports necessary functions for parsing SQL, finding table names across Redash queries, and formatting/printing results. This module is typically used via its CLI. ```python from redash_toolbelt.examples.find_table_names import ( extract_table_names, find_table_names, format_query, print_summary, print_details ) ``` -------------------------------- ### Redash Migration Flow Diagram Source: https://github.com/getredash/redash-toolbelt/blob/master/redash_toolbelt/docs/redash-migrate/README.md This diagram illustrates the data flow during a Redash migration, showing GET requests from the origin instance to the redash-migrate tool and POST requests from the tool to the destination instance. ```text ┌───────────────────┐ ┌───────────────────┐ │ │ │ │ │ │ │ │ │ Origin Redash │ .─────────────────. │Destination Redash │ │ Instance │◀───────GET───────( redash-migrate )───────POST───────▶│ Instance │ │ │ `─────────────────' │ │ │ │ │ │ └───────────────────┘ └───────────────────┘ ``` -------------------------------- ### Python: Fetch Redash query definition and parameters Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/03-date-ranges.md Demonstrates how to initialize a Redash client and retrieve the definition and parameter metadata for a specific query. ```python client = Redash(url, key) query = client.get_query(query_id) parameters = query['options'].get('parameters', []) ``` -------------------------------- ### Internal HTTP GET Request Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/01-redash-client.md Low-level HTTP GET request wrapper. Used internally but available for direct API calls. Returns a raw `requests.Response` object; call `.json()` to decode. ```python def _get(self, path: str, **kwargs) -> requests.Response ``` ```python # Fetch query results response = client._get('api/queries/123/results') results = response.json() # Raw API call response = client._get('api/data_sources/1/schema') schema = response.json() ``` -------------------------------- ### Date Ranges Utility Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Get predefined date range values for use in Redash queries. ```APIDOC ## Date Ranges ### Description Provides access to predefined date ranges commonly used in Redash. ### Function ```python from redash_toolbelt import get_frontend_vals dates = get_frontend_vals() ``` ### Returns A named tuple containing various date range objects, each with `start` and `end` attributes. Example attributes include: - `d_this_week`, `d_this_month`, `d_this_year` - `d_last_week`, `d_last_month`, `d_last_year` - `d_last_7_days`, `d_last_14_days`, `d_last_30_days`, `d_last_60_days`, `d_last_90_days` - `d_now`, `d_yesterday` ``` -------------------------------- ### Entry Point Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/API-EXPORTS.md The main entry point for the `redash-migrate` CLI command. ```APIDOC ## Entry Point ### `main(command: str) -> None` Parses the command-line argument and executes the corresponding migration command. ``` -------------------------------- ### Connect to Redash and Test Credentials Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Establishes a connection to a Redash instance and verifies the provided API key. Ensure you have your Redash URL and API key ready. ```python from redash_toolbelt import Redash client = Redash('https://app.redash.io/acme', 'api_key') if not client.test_credentials(): raise ValueError("Invalid API key") ``` -------------------------------- ### CLI Entry Points Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/MANIFEST.txt The toolbelt provides several CLI entry points for common tasks and migrations. ```APIDOC ## CLI Entry Points ### Description The Redash Toolbelt includes command-line interface (CLI) entry points for various administrative and utility tasks, including migrations. ### Migration Commands - `redash-migrate init`: Initializes the migration process by creating a `meta.json` file. ### Usage Refer to `05-migrate-tool.md` for detailed instructions on using the migration commands. ``` -------------------------------- ### Initialize Redash Migration Tool Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Initializes the Redash migration tool. This command is typically run interactively to set up the migration process. ```bash # CLI only redash-migrate init redash-migrate data-sources redash-migrate users redash-migrate queries # ... etc ``` -------------------------------- ### CLI Prompt for API Key Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md Demonstrates how CLI tools might prompt for an API key if not provided via environment variables. ```bash # Most CLI tools will prompt if not provided export REDASH_API_KEY='...' find-tables https://app.redash.io/acme 1 ``` -------------------------------- ### Basic redash-migrate Command Structure Source: https://github.com/getredash/redash-toolbelt/blob/master/redash_toolbelt/docs/redash-migrate/README.md Illustrates the fundamental syntax for running the redash-migrate command with a specified command. This tool is used for moving data between Redash instances. ```bash redash-migrate [COMMAND] ``` -------------------------------- ### Redash Client Initialization Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/API-EXPORTS.md Initialize the Redash client with your Redash URL and API key. ```APIDOC ## Redash Client ### Description Initializes the Redash client with the Redash instance URL and an API key. ### Constructor - `__init__(self, redash_url: str, api_key: str) -> None` ### Parameters - **redash_url** (str) - The URL of your Redash instance. - **api_key** (str) - Your Redash API key. ``` -------------------------------- ### Get Specific Redash Alert Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/01-redash-client.md Fetches the details of a single alert using its unique ID. Requires the alert ID as input. ```python alert = client.get_alert(5) print(f"Alert checks query {alert['query_id']}") ``` -------------------------------- ### Redash Migration Tool Core Commands Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/05-migrate-tool.md Lists the available commands for the `redash-migrate` CLI tool. These commands cover initialization, data source management, object migration, and post-migration cleanup tasks. Most commands require a pre-configured `meta.json` file. ```bash redash-migrate init # Create meta.json template redash-migrate data-sources # Create stub data sources redash-migrate check-data-sources # Validate data source mapping redash-migrate users # Migrate user accounts redash-migrate groups # Migrate groups and permissions redash-migrate queries # Migrate queries redash-migrate visualizations # Migrate visualizations redash-migrate dashboards # Migrate dashboards redash-migrate destinations # Migrate alert destinations redash-migrate alerts # Migrate alerts redash-migrate favorites # Migrate favorite flags redash-migrate disable-users # Disable users at destination redash-migrate fix-qrds-refs # Fix query result data source references redash-migrate fix-csv-queries # Convert csvurl queries to csv format ``` -------------------------------- ### Initialize Redash Client Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Instantiate the Redash client with your Redash URL and API key. This client is used for all subsequent interactions with the Redash API. ```python from redash_toolbelt import Redash client = Redash(redash_url, api_key) ``` -------------------------------- ### Lookup.lookup() Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/04-query-utilities.md Scans all queries and dashboards in the instance and prints matching URLs to stdout. Uses click progress bars for visual feedback. ```APIDOC ## Lookup.lookup() ### Description Scans all queries and dashboards in the instance, prints matching URLs to stdout. Uses `click` progress bars for visual feedback. ### Parameters - **—** (—) - Required - No parameters ### Returns - **None** - Prints URLs to stdout ### Output One URL per line for each matching query or dashboard ### Request Example ```python lookup = Lookup(client, ['user@example.com']) lookup.lookup() # Output: # https://app.redash.io/acme/queries/123 # https://app.redash.io/acme/dashboards/my-dashboard ``` ``` -------------------------------- ### Handle HTTP Errors in Python Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md Catch and handle `requests.exceptions.HTTPError` when interacting with the Redash API. This example shows how to check for specific status codes like 404. ```python import requests try: client.get_query(999) except requests.exceptions.HTTPError as e: if e.response.status_code == 404: print("Query not found") else: print(f"Error: {e.response.status_code}") ``` -------------------------------- ### Secure Redash Migration with Environment Variables Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md Demonstrates a secure approach to Redash migration by using environment variables for API keys and restricting file permissions. This prevents sensitive keys from being exposed. ```bash # Use environment variables export REDASH_API_KEY='origin_admin_key' export REDASH_DEST_KEY='dest_admin_key' # Never store keys in files redash-migrate init # Interactive prompt (keys not echoed) # Immediately restrict meta.json chmod 600 meta.json # Clean up after migration unset REDASH_API_KEY REDASH_DEST_KEY ``` -------------------------------- ### Get User API Key Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/05-migrate-tool.md Fetches the API key for a given user ID from a Redash client. This is used internally to create per-user clients for specific operations. ```python def get_api_key(client: Redash, user_id: int) -> str: pass ``` -------------------------------- ### Basic Redash Client Usage Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/README.md Instantiate the Redash client and test credentials. This client is used for interacting with the Redash API. ```python from redash_toolbelt import Redash client = Redash('https://app.redash.io/acme', 'your_api_key') # Test connection if client.test_credentials(): print("Connected!") # Get all queries all_queries = client.paginate(client.queries) print(f"Found {len(all_queries)} queries") ``` -------------------------------- ### Perform Full Instance Lookup Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/04-query-utilities.md Scans all queries and dashboards in the Redash instance and prints matching URLs to stdout. Uses click progress bars for visual feedback. No parameters are required. ```python lookup = Lookup(client, ['user@example.com']) lookup.lookup() ``` -------------------------------- ### Lookup Class Initialization Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/04-query-utilities.md Initializes the Lookup class with an authenticated Redash client and a list of email addresses to search for. ```APIDOC ## Lookup Class ### Description Encapsulates search logic for finding references to a list of email addresses across queries and dashboards. ### Parameters #### Path Parameters - **redash** (Redash) - Required - Authenticated Redash client - **email_list** (list[str]) - Required - List of email addresses to search for (lowercased internally) ### Request Example ```python from redash_toolbelt import Redash from redash_toolbelt.examples.gdpr_scrub import Lookup client = Redash('https://app.redash.io/acme', 'my_api_key') lookup = Lookup(client, ['user@example.com', 'admin@company.com']) ``` ``` -------------------------------- ### Format Date Range for Queries Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Extract start and end dates from a predefined date range (e.g., last 30 days) and format them as 'YYYY-MM-DD' strings for use in Redash queries. ```python from redash_toolbelt import get_frontend_vals dates = get_frontend_vals() start = dates.d_last_30_days.start.strftime('%Y-%m-%d') end = dates.d_last_30_days.end.strftime('%Y-%m-%d') ``` -------------------------------- ### Initialize Lookup Class Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/04-query-utilities.md Encapsulates search logic for finding references to a list of email addresses across queries and dashboards. Requires an authenticated Redash client and a list of email addresses to search for. ```python from redash_toolbelt import Redash from redash_toolbelt.examples.gdpr_scrub import Lookup client = Redash('https://app.redash.io/acme', 'my_api_key') lookup = Lookup(client, ['user@example.com', 'admin@company.com']) ``` -------------------------------- ### Get Frontend Date Range Values Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Retrieve a named tuple containing various predefined date ranges and singletons commonly used in frontend applications. Useful for consistent date filtering. ```python from redash_toolbelt import get_frontend_vals dates = get_frontend_vals() ``` -------------------------------- ### Fetch All Queries with Pagination Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md This snippet demonstrates how to fetch all queries from Redash, automatically handling pagination. It's useful for bulk analysis or processing all available queries. ```python from redash_toolbelt import Redash client = Redash(url, key) # Fetch all queries (handles pagination automatically) all_queries = client.paginate(client.queries, page_size=100) for query in all_queries: print(f"{query['id']}: {query['name']} ({query['data_source_id']})") ``` -------------------------------- ### Execute Redash Query and Get Results Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/04-query-utilities.md Executes a Redash query with specified parameters and retrieves the result rows. This function blocks until the query completes. Ensure the provided API key has query execution permissions. ```python from redash_toolbelt.examples.refresh_query import get_fresh_query_result rows = get_fresh_query_result( 'https://app.redash.io/acme', query_id=123, api_key='my_api_key', params={'start_date': '2026-01-01', 'end_date': '2026-07-02'} ) for row in rows: print(row) ``` -------------------------------- ### Get All Redash Date Ranges Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/03-date-ranges.md Returns a named tuple containing all dynamic date ranges and singletons supported by Redash's front-end date picker. All values are calculated relative to today's date at call time. Used for parameterized queries. ```python from redash_toolbelt import get_frontend_vals Values( d_this_week=DateRange(start=datetime(2026, 7, 6), end=datetime(2026, 7, 12)), d_this_month=DateRange(start=datetime(2026, 7, 1), end=datetime(2026, 7, 31)), # ... other ranges ... d_now=datetime(2026, 7, 2), d_yesterday=datetime(2026, 7, 1) ) ``` ```python DateRange( start=datetime(...), # Can be accessed as .start end=datetime(...) # Can be accessed as .end ) ``` -------------------------------- ### _get(), _post(), _delete() Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/01-redash-client.md Low-level HTTP request wrappers. Used internally but available for direct API calls. ```APIDOC ## _get(), _post(), _delete() ### Description Low-level HTTP request wrappers. Used internally but available for direct API calls. ### Parameters - **path** (str) - Required - API path (relative to base URL, e.g., `api/queries/123`) - **kwargs** (dict) - Optional - Passed to `requests.Session.request()` (e.g., `params=`, `json=`, `data=`) ### Returns `requests.Response` — Raw response; calls `.json()` to decode ### Raises `requests.exceptions.HTTPError` if status code is not 2xx (via `raise_for_status()`) ### Example ```python # Fetch query results response = client._get('api/queries/123/results') results = response.json() # Raw API call response = client._get('api/data_sources/1/schema') schema = response.json() ``` ``` -------------------------------- ### user_with_api_key() Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/05-migrate-tool.md Looks up a destination user by origin ID, fetches their API key, and creates a user entry in meta['users'] with the API key. ```APIDOC ## user_with_api_key() ### Description Looks up a destination user by origin ID and fetches their API key. Creates a user entry in `meta['users']` with the API key. ### Parameters #### Path Parameters - **origin_user_id** (int) - Required - Origin user ID - **dest_client** (Redash) - Required - Destination instance client (must be admin) ### Returns `dict` — User object with `api_key` field ### Raises `UserNotFoundException` if origin user not found in `meta['users']` ``` -------------------------------- ### Import Data Sources Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/05-migrate-tool.md Creates stub data sources in the destination Redash instance based on origin data sources. Handles type conversions for unsupported types, such as 'csvurl' to 'csv'. Updates meta['data_sources']. ```python def import_data_sources(orig_client: Redash, dest_client: Redash) -> None: pass ``` -------------------------------- ### Redash Migration Commands Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Provides a suite of subcommands for migrating Redash instances, including initialization, data source management, user and group synchronization, and fixing references. ```bash redash-migrate init ``` ```bash redash-migrate data-sources ``` ```bash redash-migrate check-data-sources ``` ```bash redash-migrate users ``` ```bash redash-migrate groups ``` ```bash redash-migrate queries ``` ```bash redash-migrate visualizations ``` ```bash redash-migrate dashboards ``` ```bash redash-migrate destinations ``` ```bash redash-migrate alerts ``` ```bash redash-migrate favorites ``` ```bash redash-migrate disable-users ``` ```bash redash-migrate fix-qrds-refs ``` ```bash redash-migrate fix-csv-queries ``` -------------------------------- ### Python: Fill dynamic parameter values for Redash queries Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/03-date-ranges.md This code snippet shows how to iterate through query parameters, identify dynamic date parameters using `get_frontend_vals()`, and format their values for execution. ```python from redash_toolbelt import get_frontend_vals dates = get_frontend_vals() params = {} for param in parameters: param_name = param['name'] param_type = param['type'] param_value = param['value'] # Default value from query # Check if this is a dynamic date parameter if 'date' in param_type and param_value in dates._fields: dynamic_val = getattr(dates, param_value) # Format based on whether it's a range or singleton if hasattr(dynamic_val, 'start'): params[param_name] = { 'start': dynamic_val.start.strftime('%Y-%m-%d'), 'end': dynamic_val.end.strftime('%Y-%m-%d') } else: params[param_name] = dynamic_val.strftime('%Y-%m-%d') else: params[param_name] = param_value ``` -------------------------------- ### Export All Queries CLI Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/04-query-utilities.md Export all queries from a Redash instance using this CLI command. It requires the Redash instance URL and an API key. The output will be a collection of all queries. ```bash # Export all queries export-queries https://app.redash.io/acme [--api-key KEY] ``` -------------------------------- ### Troubleshooting Redash Query Failures Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Addresses issues where Redash queries fail due to unmapped data sources. Suggests running the data source migration first. ```text Query fails | Unmapped data source | Run data source migration first ``` -------------------------------- ### print_details() Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/04-query-utilities.md Prints detailed output of (query_id, table_name) pairs, useful for the `find-tables` CLI script when the `--detail` flag is used. ```APIDOC ## print_details() ### Description Prints detailed output showing each (query_id, table_name) pair. Used by the `find-tables` CLI script with `--detail` flag. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature `def print_details(tables_by_qry: dict[int, list[str]]) -> None` ### Parameters - **tables_by_qry** (dict[int, list[str]]) - Required - Output from `find_table_names()` ### Returns - **None** - Prints to stdout ### Example: ```python # Assuming tables_by_query is the output from find_table_names() tables_by_query = {1: ['users', 'orders'], 2: ['users'], 3: ['items']} print_details(tables_by_query) # Output: # 1,users # 1,orders # 2,users # 3,items ``` ``` -------------------------------- ### View and Check meta.json During Migration Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/06-configuration-and-setup.md Inspect the contents of the meta.json file during a migration process. Use `cat` and `grep` to view the current state or specific mappings. ```bash # View current state cat meta.json | python -m json.tool # Check specific mappings cat meta.json | grep '"queries"' ``` -------------------------------- ### Import Visualizations Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/05-migrate-tool.md Migrates visualizations for all imported queries. Handles the default table visualization specially. This function is idempotent and preserves visualization details. ```python def import_visualizations(orig_client: Redash, dest_client: Redash) -> None: pass ``` -------------------------------- ### Full Redash Migration Workflow Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Executes a comprehensive migration workflow for Redash, including initialization, data source checks, user imports, and more. Rate limiting can be disabled for faster migration. ```bash export REDASH_RATE_LIMIT_ENABLED=false redash-migrate init # Interactive setup redash-migrate data-sources redash-migrate check-data-sources redash-migrate users redash-migrate groups redash-migrate queries redash-migrate visualizations redash-migrate dashboards redash-migrate alerts redash-migrate favorites export REDASH_RATE_LIMIT_ENABLED=true ``` -------------------------------- ### Find User by Origin ID and Fetch API Key Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/05-migrate-tool.md Looks up a user in the destination instance using their original user ID and retrieves their API key. It also creates a user entry in 'meta['users']' if it doesn't exist. Raises UserNotFoundException if the origin user is not found. ```python def user_with_api_key(origin_user_id: int, dest_client: Redash) -> dict: pass ``` -------------------------------- ### Test Credentials Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/API-EXPORTS.md Verifies the provided API key and Redash URL are valid. ```APIDOC ## Session & Auth ### `test_credentials` Tests if the provided Redash URL and API key are valid by making a test API call. - **Returns** - `bool` - True if credentials are valid, False otherwise. ``` -------------------------------- ### Python: Execute Redash query with filled parameters Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/03-date-ranges.md This snippet shows how to make a POST request to the Redash API to execute a query with the dynamically filled parameters, forcing a fresh result. ```python client._post(f'api/queries/{query_id}/results', json={ 'parameters': params, 'max_age': 0 # Force fresh execution }) ``` -------------------------------- ### Complete Redash Migration Workflow Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/05-migrate-tool.md This script provides a comprehensive workflow for migrating a Redash instance. It includes initialization, validation, disabling rate limits, migrating various components in order, handling specific cases like csvurl, re-enabling rate limits, and reviewing the meta.json file. ```bash # 1. Initialize configuration redash-migrate init # Follow prompts to enter origin/destination URLs and admin keys # 2. Validate setup redash-migrate check-data-sources # 3. Disable rate limiting (important!) export REDASH_RATE_LIMIT_ENABLED=false # 4. Migrate in order redash-migrate data-sources redash-migrate users redash-migrate groups redash-migrate queries redash-migrate visualizations redash-migrate dashboards redash-migrate destinations redash-migrate alerts redash-migrate favorites redash-migrate disable-users redash-migrate fix-qrds-refs # 5. Handle csvurl if migrating from app.redash.io redash-migrate fix-csv-queries # 6. Re-enable rate limiting export REDASH_RATE_LIMIT_ENABLED=true # 7. Review meta.json for any SKIP/ERROR messages cat meta.json ``` -------------------------------- ### Fetch All Redash Resources Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Retrieves all queries, dashboards, or users from a Redash instance using pagination. Adjust page_size for optimal performance. ```python # Queries all_queries = client.paginate(client.queries, page_size=100) # Dashboards all_dashboards = client.paginate(client.dashboards, page_size=100) # Users all_users = client.paginate(client.users, page_size=50) ``` -------------------------------- ### Fetch All Data Sources Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/01-redash-client.md Use this function to retrieve a list of all data sources configured in your Redash instance. Each data source object contains its ID, name, type, and configuration options. ```python for ds in client.get_data_sources(): print(f"{ds['id']}: {ds['name']} ({ds['type']})") ``` -------------------------------- ### Schedule Object - String Format (Legacy) Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/02-types.md Legacy string format for query schedules, representing refresh intervals in seconds or a specific time of day for daily refreshes. ```python # Examples: # "3600" → every hour # "86400" → daily # "15:30" → daily at 15:30 UTC ``` -------------------------------- ### Export Redash Queries Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/00-index.md Exports queries from a Redash instance. Requires the Redash URL and an optional API key. ```bash export-queries URL [--api-key KEY] ``` -------------------------------- ### Import Users Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/05-migrate-tool.md Migrates user accounts between Redash instances, matching by email and skipping the admin user. Creates destination users with no email invitation and preserves their enabled/disabled status. Updates meta['users']. ```python def import_users(orig_client: Redash, dest_client: Redash) -> None: pass ``` -------------------------------- ### Print Detailed Query Table Name Pairs Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/04-query-utilities.md Prints detailed output of each (query_id, table_name) pair. This is used by the 'find-tables' CLI script with the '--detail' flag. ```python print_details(tables_by_query) # Output: # 123,users # 123,orders # 124,users # 125,items ``` -------------------------------- ### Export Redash Queries to SQL Files Source: https://github.com/getredash/redash-toolbelt/blob/master/_autodocs/04-query-utilities.md Use `save_queries` to export all queries from a Redash instance. Each query is saved as a separate .sql file with metadata comments. Requires a list of query objects obtained from `client.paginate(client.queries)`. ```python from redash_toolbelt import Redash from redash_toolbelt.examples.query_export import save_queries client = Redash('https://app.redash.io/acme', 'my_api_key') all_queries = client.paginate(client.queries) save_queries(all_queries) # Creates: query_1.sql, query_2.sql, etc. ```