A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Add integrations section and example for Google Cloud Storage, Google Cloud BigQuery, Google Sheets (#310)
Myles Scolnick35aa1662c6cd
diff --git a/docs/index.md b/docs/index.mdindex 2ccdbfab54..25b6723b0d 100644--- a/docs/index.md+++ b/docs/index.md@@ -24,7 +24,6 @@ _These features accelerate data work, increase reproducibility by eliminatinghidden state, transform notebooks into interactive tools, and make notebookinga delight._-marimo was built from the ground up to solve many <ahref="/faq.html#faq-jupyter">well-known problems associated with traditionalnotebooks</a>.@@ -70,6 +69,7 @@ notebooks</a>.getting_started/indexguides/indexapi/index+ integrations/indexexamplesfaqcommunitydiff --git a/docs/integrations/google_cloud_bigquery.md b/docs/integrations/google_cloud_bigquery.mdnew file mode 100644index 0000000000..454acd5d14--- /dev/null+++ b/docs/integrations/google_cloud_bigquery.md@@ -0,0 +1,72 @@+# Google Cloud BigQuery++## Getting Started++To use Google Cloud BigQuery as a data source, you will need to install the `google-cloud-bigquery` Python package. You can install this package using `pip`:++```bash+pip install google-cloud-bigquery db-dtypes+```++## Authentication++### Application Default Credentials (Recommended)++The easiest way to authenticate with Google Cloud BigQuery is to use [Application Default Credentials](https://cloud.google.com/docs/authentication/production). If you are running marimo on Google Cloud and your resource has a service account attached, then Application Default Credentials will automatically be used.+If you are running marimo locally, you can authenticate with Application Default Credentials by running the following command:++```bash+gcloud auth application-default login+```++### Service Account Key File++To authenticate with Google Cloud BigQuery, you will need to create a service account and download the service account key file. You can create a service account and download the key file by following the instructions [here](https://cloud.google.com/iam/docs/creating-managing-service-account-keys).++Once you have downloaded the key file, you can authenticate with Google Cloud BigQuery by setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of the key file:++```bash+export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key/file.json+```++## Reading Data++To read data from Google Cloud BigQuery, you will need to create a `BigQueryClient` object. You can then use this object to read data from Google Cloud BigQuery.++```python+# Cell 1 - Load libraries+import marimo as mo+from google.cloud import bigquery++# Cell 2 - Load datasets+client = bigquery.Client()+datasets = list(client.list_datasets())++# Cell 3 - Select dataset+selected_dataset = mo.ui.dropdown(+ label="Select dataset", options=[d.dataset_id for d in datasets]+)+selected_dataset++# Cell 4 - Load tables+dataset = client.dataset(selected_dataset.value)+tables = list(client.list_tables(dataset))+selected_table = mo.ui.dropdown(+ label="Select table", options=[t.table_id for t in tables]+)+selected_table++# Cell 5 - Load table data+results = client.list_rows(dataset.table(selected_table.value), max_results=10)+mo.ui.table(results.to_dataframe(), selection=None)+```++## Example++Check out our full example using Google Cloud BigQuery [here](https://github.com/marimo-team/marimo/blob/main/examples/integrations/google_cloud_bigquery.py)++Or run it yourself:++```bash+marimo run https://raw.githubusercontent.com/marimo-team/marimo/main/examples/integrations/google_cloud_bigquery.py+```diff --git a/docs/integrations/google_cloud_storage.md b/docs/integrations/google_cloud_storage.mdnew file mode 100644index 0000000000..6a5666006a--- /dev/null+++ b/docs/integrations/google_cloud_storage.md@@ -0,0 +1,73 @@+# Google Cloud Storage++## Getting Started++To use Google Cloud Storage as a data source, you will need to install the `google-cloud-storage` Python package. You can install this package using `pip`:++```bash+pip install google-cloud-storage+```++## Authentication++### Application Default Credentials (Recommended)++The easiest way to authenticate with Google Cloud Storage is to use [Application Default Credentials](https://cloud.google.com/docs/authentication/production). If you are running marimo on Google Cloud and your resource has a service account attached, then Application Default Credentials will automatically be used.+If you are running marimo locally, you can authenticate with Application Default Credentials by running the following command:++```bash+gcloud auth application-default login+```++### Service Account Key File++To authenticate with Google Cloud Storage, you will need to create a service account and download the service account key file. You can create a service account and download the key file by following the instructions [here](https://cloud.google.com/iam/docs/creating-managing-service-account-keys).++Once you have downloaded the key file, you can authenticate with Google Cloud Storage by setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of the key file:++```bash+export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key/file.json+```++## Reading Data++To read data from Google Cloud Storage, you will need to create a `StorageClient` object. You can then use this object to read data from Google Cloud Storage.++```python+# Cell 1 - Load libraries+import marimo as mo+from google.cloud import storage++# Cell 2 - Load buckets+client = storage.Client()+buckets = client.list_buckets()++# Cell 3 - Select bucket+selected_bucket = mo.ui.dropdown(+ label="Select bucket", options=[b.name for b in buckets]+)+selected_bucket++# Cell 4 - Load files+files = list(bucket.list_blobs())+items = [+ {+ "Name": f.name,+ "Updated": f.updated.strftime("%h %d, %Y"),+ "Size": f.size,+ }+ for f in files+]+file_table = mo.ui.table(items, selection="single")+file_table if items else mo.md("No files found").callout()+```++## Example++Check out our full example using Google Cloud Storage [here](https://github.com/marimo-team/marimo/blob/main/examples/integrations/google_cloud_storage.py)++Or run it yourself:++```bash+marimo run https://raw.githubusercontent.com/marimo-team/marimo/main/examples/integrations/google_cloud_storage.py+```diff --git a/docs/integrations/google_sheets.md b/docs/integrations/google_sheets.mdnew file mode 100644index 0000000000..227eaa05c6--- /dev/null+++ b/docs/integrations/google_sheets.md@@ -0,0 +1,67 @@+# Google Sheets++## Getting Started++To use Google Sheets as a data source, you will need to install the `gspread` and `oauth2client` Python packages. You can install this package using `pip`:++```bash+pip install gspread oauth2client+```++## Authentication++### Application Default Credentials (Recommended)++The easiest way to authenticate with Google Sheets is to use [Application Default Credentials](https://cloud.google.com/docs/authentication/production). If you are running marimo on Google Cloud and your resource has a service account attached, then Application Default Credentials will automatically be used.+If you are running marimo locally, you can authenticate with Application Default Credentials by running the following command:++```bash+gcloud auth application-default login+```++### Service Account Key File++To authenticate with Google Sheets, you will need to create a service account and download the service account key file. You can create a service account and download the key file by following the instructions [here](https://cloud.google.com/iam/docs/creating-managing-service-account-keys).++Once you have downloaded the key file, you can authenticate with Google Sheets by setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of the key file:++```bash+export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key/file.json+```++## Reading Data++To read data from Google Sheets, you will need to authenticate and create a `gspread.Client`. You can then use this object to read data from Google Sheets.++```python+# Cell 1 - Load libraries+import marimo as mo+import pandas as pd+import os+import gspread+from oauth2client.service_account import ServiceAccountCredentials++# Authenticate with Google Sheets+scope = [+ "https://spreadsheets.google.com/feeds",+ "https://www.googleapis.com/auth/drive",+]+credentials = ServiceAccountCredentials.from_json_keyfile_name(+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"], scope+)+gc = gspread.authorize(credentials)++# Cell 2 - Load the sheet+wks = gc.open("marimo").sheet1+mo.ui.table(pd.DataFrame(wks.get_all_records()))+```++## Example++Check out our full example using Google Sheets [here](https://github.com/marimo-team/marimo/blob/main/examples/integrations/google_sheets.py)++Or run it yourself:++```bash+marimo run https://raw.githubusercontent.com/marimo-team/marimo/main/examples/integrations/google_sheets.py+```diff --git a/docs/integrations/index.md b/docs/integrations/index.mdnew file mode 100644index 0000000000..f0f3bfaf82--- /dev/null+++ b/docs/integrations/index.md@@ -0,0 +1,19 @@+# Integrations++```{eval-rst}+.. toctree::+ :maxdepth: 2+ :hidden:++ google_cloud_storage+ google_cloud_bigquery+ google_sheets+```++It is easy to integrate your preferred data sources with marimo. Since marimo is strictly Python, you can utilize any Python library to access your data. In this section, we provide some examples of how to integrate with popular data sources.++| | |+| :--------------------------- | :------------------------------------- |+| {doc}`google_cloud_storage` | Integrating with Google Cloud Storage |+| {doc}`google_cloud_bigquery` | Integrating with Google Cloud BigQuery |+| {doc}`google_sheets` | Integrating with Google Sheets |diff --git a/examples/integrations/google_cloud_bigquery.py b/examples/integrations/google_cloud_bigquery.pynew file mode 100644index 0000000000..ff43899d97--- /dev/null+++ b/examples/integrations/google_cloud_bigquery.py@@ -0,0 +1,100 @@+import marimo++__generated_with = "0.1.43"+app = marimo.App(width="full")+++def __():+ # Imports+ import marimo as mo+ import os+ from google.cloud import bigquery+ return bigquery, mo, os+++def __(mo):+ mo.md(+ f"""+ # Google Cloud BigQuery++ Required dependencies:+ ```sh+ $ pip install google-cloud-bigquery db-dtypes+ ```+ """+ )+ return+++def __(mo):+ # Configuration+ credentials = mo.ui.text(label="(Optional) Path to credentials file").form()+ mo.accordion(+ {+ "⚙️ Configuration": mo.md(+ f"""+ This app requires a Google Cloud Platform account and a bucket to access. You will need to be authenticated with `gcloud auth login`,+ or provide a path to a credentials file.++ {credentials}+ """+ )+ }+ )+ return credentials,+++def __(bigquery, credentials, os):+ # Set up client+ if credentials.value:+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials.value+ else:+ os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)++ client = bigquery.Client()+ datasets = list(client.list_datasets())+ return client, datasets+++def __(datasets, mo):+ # Dataset selection+ selected_dataset = mo.ui.dropdown(+ label="Select dataset", options=[d.dataset_id for d in datasets]+ )+ selected_dataset+ return selected_dataset,+++def __(client, mo, selected_dataset):+ mo.stop(not selected_dataset.value)++ dataset = client.dataset(selected_dataset.value)+ return dataset,+++def __(client, dataset, mo):+ # Table selection+ tables = list(client.list_tables(dataset))+ selected_table = mo.ui.dropdown(+ label="Select table", options=[t.table_id for t in tables]+ )+ selected_table+ return selected_table, tables+++def __(client, dataset, mo, selected_table):+ results = client.list_rows(dataset.table(selected_table.value), max_results=10)+ mo.ui.table(results.to_dataframe(), selection=None)+ return results,+++if __name__ == "__main__":+ app.run()diff --git a/examples/integrations/google_cloud_storage.py b/examples/integrations/google_cloud_storage.pynew file mode 100644index 0000000000..c806c93624--- /dev/null+++ b/examples/integrations/google_cloud_storage.py@@ -0,0 +1,151 @@+import marimo++__generated_with = "0.1.43"+app = marimo.App(width="full")+++def __():+ # Imports+ import marimo as mo+ import os+ from google.cloud import storage+ return mo, os, storage+++def __(mo):+ mo.md(+ f"""+ # Google Cloud Storage++ Required dependencies:+ ```sh+ $ pip install google-cloud-storage+ ```+ """+ )+ return+++def __(mo):+ # Configuration+ credentials = mo.ui.text(label="(Optional) Path to credentials file").form()+ mo.accordion(+ {+ "⚙️ Configuration": mo.md(+ f"""+ This app requires a Google Cloud Platform account and a bucket to access. You will need to be authenticated with `gcloud auth login`,+ or provide a path to a credentials file.++ {credentials}+ """+ )+ }+ )+ return credentials,+++def __(credentials, os, storage):+ # Set up client+ if credentials.value:+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials.value+ else:+ os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)++ client = storage.Client()+ buckets = client.list_buckets()+ return buckets, client+++def __(buckets, mo):+ # Bucket selection+ selected_bucket = mo.ui.dropdown(+ label="Select bucket", options=[bucket.name for bucket in buckets]+ )+ selected_bucket+ return selected_bucket,+++def __(mo):+ get_prefix, set_prefix = mo.state("")+ return get_prefix, set_prefix+++def __(client, mo, selected_bucket):+ mo.stop(not selected_bucket.value)++ bucket = client.get_bucket(selected_bucket.value)+ return bucket,+++def __(bucket, get_prefix):+ _prefix = get_prefix() or None+ blobs = list(bucket.list_blobs(max_results=20, prefix=_prefix))+ return blobs,+++def __(get_prefix, mo, set_prefix):+ output = None+ _prefix = get_prefix()+ if _prefix:+ output = mo.hstack(+ [+ mo.md(f"Showing files in: **`{_prefix}`**"),+ mo.ui.button(label="Clear", on_click=lambda _: set_prefix(None)),+ ]+ )+ output+ return output,+++def __(blobs, bucket, mo, set_prefix):+ # Display files in a table+ _files = [+ {+ "Filter": mo.ui.button(+ label="Filter",+ on_change=lambda _: set_prefix(blob.name),+ value=blob.name,+ )+ if blob.name.endswith("/")+ else None,+ "Name": blob.name,+ "Updated": blob.updated.strftime("%h %d, %Y"),+ "Url": mo.Html(+ f'<a href="https://storage.cloud.google.com/{bucket.name}/{blob.name}" target="_blank">🔗 Link</a>'+ ),+ "Size": blob.size,+ }+ for blob in blobs+ ]+ file_table = mo.ui.table(_files, selection="single")+ file_table if _files else mo.md("No files found").callout()+ return file_table,+++def __(bucket, file_table, mo):+ # Load selected file+ if len(file_table.value) >= 1:+ _selected_file = file_table.value[0]+ _blob = bucket.get_blob(_selected_file["Name"])+ if (+ _blob.content_type and _blob.content_type.startswith("image")+ ) or _blob.name.endswith(".png"):+ mo.output.replace(mo.image(_blob.download_as_string()))+ else:+ mo.output.replace(mo.plain_text(_blob.download_as_text()))+ return+++if __name__ == "__main__":+ app.run()diff --git a/examples/integrations/google_sheets.py b/examples/integrations/google_sheets.pynew file mode 100644index 0000000000..62712d1770--- /dev/null+++ b/examples/integrations/google_sheets.py@@ -0,0 +1,98 @@+import marimo++__generated_with = "0.1.43"+app = marimo.App(width="full")+++def __():+ # Imports+ import marimo as mo+ import pandas as pd+ import os+ import gspread+ from oauth2client.service_account import ServiceAccountCredentials+ from oauth2client.client import GoogleCredentials+ return GoogleCredentials, ServiceAccountCredentials, gspread, mo, os, pd+++def __(mo):+ mo.md(+ f"""+ # Google Sheets++ Required dependencies:+ ```sh+ $ pip install gspread+ ```+ """+ )+ return+++def __(mo):+ # Configuration+ credentials = mo.ui.text(label="(Optional) Path to credentials file").form()+ mo.accordion(+ {+ "⚙️ Configuration": mo.md(+ f"""+ This app requires a Google Cloud Platform account and a bucket to access. You will need to be authenticated with `gcloud auth login`,+ or provide a path to a credentials file.++ {credentials}+ """+ )+ }+ )+ return credentials,+++def __(+ GoogleCredentials,+ ServiceAccountCredentials,+ credentials,+ gspread,+ os,+):+ # Set up client+ _scopes = [+ "https://spreadsheets.google.com/feeds",+ "https://www.googleapis.com/auth/drive",+ ]+ if credentials.value:+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials.value+ creds = ServiceAccountCredentials.from_json_keyfile_name(+ credentials.value,+ _scopes,+ )+ else:+ os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)+ creds = GoogleCredentials.get_application_default().create_scoped(_scopes)++ gc = gspread.authorize(creds)+ return creds, gc+++def __(mo):+ spreadsheet_url = mo.ui.text_area(label="Spreadsheet URL").form()+ spreadsheet_url+ return spreadsheet_url,+++def __(gc, mo, pd, spreadsheet_url):+ mo.stop(not spreadsheet_url.value)++ # Get sheet records+ wks = gc.open_by_url(spreadsheet_url.value).sheet1+ mo.ui.table(pd.DataFrame(wks.get_all_records()), selection=None)+ return wks,+++if __name__ == "__main__":+ app.run()