Skip to main content

Alt text

KeboolaStreamlit

KeboolaStreamlit simplifies the use of Keboola Storage API within Streamlit apps, providing easy-to-use functions for authentication, data retrieval, event logging, and data loading.

Installation

To install:

pip install keboola-streamlit

If you also need the Snowflake Integration functions, install the snowflake extra:

pip install keboola-streamlit[snowflake]

If you query the data app workspace through Query Service, install the query-service extra:

pip install keboola-streamlit[query-service]

If you are using streamlit<=1.36.0, please use version 0.0.5 of the keboola-streamlit package.

Usage

Import and Initialization

Create an instance of the KeboolaStreamlit class, and initialize it with the required parameters from Streamlit secrets:

import streamlit as st
from keboola_streamlit import KeboolaStreamlit

URL = st.secrets["KEBOOLA_URL"]
TOKEN = st.secrets["STORAGE_API_TOKEN"]

keboola = KeboolaStreamlit(root_url=URL, token=TOKEN)

Authentication and Authorization

If only selected roles can access the app, make sure the user is authorized by:

ROLE_ID = st.secrets["REQUIRED_ROLE_ID"]

keboola.auth_check(required_role_id=ROLE_ID)

Add a logout button to your app:

keboola.logout_button(sidebar=True, use_container_width=True)

💡 You can find more about authorization settings in Keboola here.

Reading Data from Keboola Storage

Read data from a Keboola Storage table and return it as a Pandas DataFrame:

df = keboola.read_table(table_id='YOUR_TABLE_ID')

💡 Wrap the function and use the st.cache_data decorator to prevent your data from being read every time you interact with the app. Learn more about caching here.

Writing Data to Keboola Storage

Write data from a Pandas DataFrame to a Keboola Storage table:

keboola.write_table(table_id='YOUR_TABLE_ID', df=your_dataframe, is_incremental=False)

Creating Events

Create an event in Keboola Storage to log activities:

keboola.create_event(message='Streamlit App Create Event', event_type='keboola_data_app_create_event')

Every event the library writes holds the logged-in user: the email (user) and, for apps with an identity provider login, the provider's user ID (user_id), which stays the same when the email changes.

Table Selection

Add a table selection interface in your app:

df = keboola.add_table_selection(sidebar=True)

Snowflake Integration

Requires the snowflake extra: pip install keboola-streamlit[snowflake]

Creating a Snowflake Session

To interact with Snowflake, first create a session using your Streamlit secrets. Ensure that the following secrets are set in your Streamlit configuration:

  • SNOWFLAKE_USER
  • SNOWFLAKE_ACCOUNT
  • SNOWFLAKE_ROLE
  • SNOWFLAKE_WAREHOUSE
  • SNOWFLAKE_DATABASE
  • SNOWFLAKE_SCHEMA

For authentication you can use password:

  • SNOWFLAKE_PASSWORD

Or key-pair:

  • SNOWFLAKE_PRIVATE_KEY
  • SNOWFLAKE_PRIVATE_KEY_PASSPHRASE (Optional)

Streamlit will automatically use type of authorization based on what you fill in secrets.

NOTE: If both password and key-pair are filled in secrets, Streamlit by default will use the key-pair authorization.

Then, create the session as follows:

st.session_state['snowflake_session'] = keboola.snowflake_create_session_object()

Reading Data from Snowflake

Load a table from Snowflake into a Pandas DataFrame:

df_snowflake = keboola.snowflake_read_table(session=st.session_state['snowflake_session'], table_id='YOUR_SNOWFLAKE_TABLE_ID')

Executing a Snowflake Query

Execute a SQL query on Snowflake and optionally return the results as a DataFrame:

query = "SELECT * FROM YOUR_SNOWFLAKE_TABLE"
df_query_result = keboola.snowflake_execute_query(session=st.session_state['snowflake_session'], query=query, return_df=True)

Writing Data to Snowflake

Write a Pandas DataFrame to a Snowflake table:

keboola.snowflake_write_table(session=st.session_state['snowflake_session'], df=your_dataframe, table_id='YOUR_SNOWFLAKE_TABLE_ID')

Query Service Integration

Requires the query-service extra: pip install keboola-streamlit[query-service]

Turn on Storage Access in the data app configuration. Keboola then creates a workspace for the app, and the app queries it through the Keboola Query Service. The workspace can read the project's Storage, and write to the tables in the app's output mapping (direct grant). No Snowflake credentials are needed in secrets.

df = keboola.query_service_execute_query(query='SELECT * FROM "in.c-main"."users" LIMIT 100')

# Statements that change data: return_df=False returns the number of affected rows, or None when the query failed.
rows_affected = keboola.query_service_execute_query(
    query='UPDATE "in.c-main"."users" SET "active" = FALSE WHERE "id" = \'42\'',
    return_df=False,
)

The library finds the workspace and the service from environment variables that Keboola sets:

  • workspace ID: the JSON file at KBC_WORKSPACE_MANIFEST_PATH, or the WORKSPACE_ID variable
  • BRANCH_ID (numeric)
  • QUERY_SERVICE_URL; when it is not set, the URL is read from the Storage API index

Each query is logged as Storage events with the logged-in user (email and user ID). The events of one query share a request_id and hold the workspace ID and branch ID:

  • keboola_data_app_query_service_query is written before the query is sent. If it cannot be written, the query is not sent, so no query runs without an audit entry.
  • keboola_data_app_query_service_query_submitted holds the Query Service job ID, to match the query with the Query Service history.
  • keboola_data_app_query_service_query_completed holds the backend query ID (backend_query_id, the Snowflake query ID), to find the query in the Snowflake query history.
  • keboola_data_app_query_service_query_failed is written when the query fails, is cancelled or times out, or its results cannot be read. It holds the error message and, when the query reached the backend, the backend query ID. A query that failed or timed out is cancelled, so it does not keep running. When the cancel has not taken effect within 30 seconds, or could not be sent, the event says so, because the query may still complete.

The events do not hold the SQL text, because it can contain personal data. Use the backend query ID to see the SQL. The error message in the failed event comes from the database and can repeat values from the query, e.g. Numeric value 'jane@example.com' is not recognized.

Results cached with st.cache_data are shared by all users of the app, and a cached call writes no events. To log every read, call query_service_execute_query without caching, or key the cache per user (see Row-level security), so each user gets their own cache entry and event.

Query Service returns every value as a string. The library converts number, boolean, date and timestamp columns to pandas types based on the column type. Integers become Int64, decimals become float64 (about 15 significant digits), and timestamps with a time zone are converted to UTC. Snowflake dates and timestamps outside the pandas range (years 1677 to 2262, e.g. 9999-12-31) become Python date and datetime objects, and then the whole column has the object type. BigQuery dates and timestamps outside that range stay as strings. Integers outside the Int64 range, columns of other types (including TIME, which Snowflake sends as seconds since midnight), and columns whose values do not match their type stay as strings. Pass convert_types=False to get only strings.

Other options:

  • refresh_metadata refreshes the Storage metadata of changed tables after the query, so Storage exports show the new data. It is on by default when return_df=False; pass refresh_metadata=True when a query with return_df=True changes data.
  • max_rows reads at most that many rows.
  • max_wait_time (seconds, default 300) after which the query is cancelled. A slow Query Service response can make the call take longer.

Query Service does not support bind parameters, so escape any user input before putting it into SQL.

For local development, set BRANCH_ID and WORKSPACE_ID (and optionally QUERY_SERVICE_URL) yourself.

Row-level security

When the user signs in through an OAuth/OIDC provider, Keboola's apps proxy adds the user token (X-Kbc-App-User-Token) to the request. query_service_execute_query sends it, together with the app's Storage token, with every Query Service request of the query. In a workspace governed by row-level security, Query Service then returns only the rows of that user. Without the token (password login, no login, local runs) only the Storage token is sent, and a governed workspace refuses the query.

When row-level security refuses a query, the app shows "You have no access to this data." and the failed event holds the error. The refusal is not retried.

The token lives 5 minutes, and Streamlit sees only the headers of the page load. So the apps proxy also adds a refresh token (X-Kbc-App-User-Refresh-Token) and the app's public URL (X-Kbc-App-Public-Url). Less than a minute before the token expires, the library gets a new one from <public URL>/_proxy/app-user-token. One call serves all queries of the session. The refresh token ends when the apps proxy closes the connection (at most after 1 hour). A token never outlives it, so in that last minute the library keeps the current token. Streamlit then reconnects at once and gets a new pair.

When the proxy refuses the refresh (the user signed out or lost access), the current token is used until it expires. After that the app shows "Your sign-in to this app has expired. Reload the page." Status and cancel requests need the user's token too (the app's Storage token does not stand for the user), so when the sign-in ends while a query runs, the query cannot be cancelled. The app then says that the query may still complete and asks the user to check the result before running it again. When the proxy is not reachable for a moment, the library tries again a few seconds later.

Key every cache per user. st.cache_data is one cache for all users of the app, keyed only by the arguments. In a governed workspace it would give one user's rows to the next user. Pass the user as an argument whose name does not start with _ (Streamlit leaves such arguments out of the key). get_app_user_key() returns the user as the token's idp and sub claims, which stay the same for every token of the user, or None without a token:

from typing import Optional, Tuple

from keboola_streamlit import get_app_user_key


@st.cache_data(ttl=300)
def load_orders(user: Optional[Tuple[str, str]]) -> pd.DataFrame:
    df = keboola.query_service_execute_query('SELECT * FROM "in.c-crm"."orders"')
    if df is None:
        # Streamlit does not cache an exception, so a failed query (e.g. an expired token) is not kept for 5 minutes.
        raise RuntimeError("The query failed.")
    return df


df = load_orders(get_app_user_key())

To call Query Service or another service yourself, use get_app_user_token(). It returns a valid token, refreshed when needed, or None without a token. Call it before every request, not once per page. It raises AppUserTokenError when the token has expired and no new one could be obtained. get_app_user_key() raises it when the token has no idp and sub.

The app does not verify the token: the apps proxy is the only one that sets the header, and it drops copies sent by the browser.

License

This project is licensed under the MIT License. See the LICENSE file for more details.

Metadata

Release files for keboola_streamlit 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for keboola_streamlit 0.4.0
File Size Uploaded Provenance Actions
keboola_streamlit-0.4.0.tar.gz 22.1 kB Without provenance Details for keboola_streamlit-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for keboola_streamlit 0.4.0
File Interpreter ABI Platform Actions
keboola_streamlit-0.4.0-py3-none-any.whl Python 3 none any Details for keboola_streamlit-0.4.0-py3-none-any.whl

Total release size: 45.5 kB

Release files / keboola_streamlit-0.4.0.tar.gz

Download URL keboola_streamlit-0.4.0.tar.gz
Size 22.1 kB
Tags Source
SHA-256 checksum
How to use checksums
6829f264e6d6dc6721925ba59b3a2be5f783f7d3d5ba82259ab24b4b9a43ee07
BLAKE2b-256 checksum
How to use checksums
256e6c8f4fd1c9b30f4024c9e194a55454fd7cc66a6842a92e58f3536e64dd59
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / keboola_streamlit-0.4.0-py3-none-any.whl

Download URL keboola_streamlit-0.4.0-py3-none-any.whl
Size 23.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b430b3a7d2260e1b4a71da77bca0c9dfc188128eea4eae3bb61e489af841a25e
BLAKE2b-256 checksum
How to use checksums
01aba766e08cde3f95445d30645aae79dbea1a5da0a98bf212a10aaf6c56a705
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for keboola_streamlit 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page