create an app to get all assets from a cognite data fusion project and display them on the screen with metadata shown
To upload files, please first save the app
import streamlit as st
import os
from cognite.client import CogniteClient
from cognite.client.services.assets import Asset
import pandas as pd
# Page config
st.set_page_config(page_title="CDF Assets Viewer", layout="wide")
# Title
st.title("Cognite Data Fusion Assets Viewer")
# Sidebar for authentication
with st.sidebar:
st.header("Authentication")
project = st.text_input("CDF Project", key="project")
client_name = st.text_input("Client Name", key="client_name")
client_id = st.text_input("Client ID", key="client_id")
client_secret = st.text_input("Client Secret", type="password", key="client_secret")
cluster = st.selectbox("Cluster", ["api", "westeurope-1", "greenfield"], key="cluster")
authenticate = st.button("Connect to CDF")
# Main content
if authenticate:
try:
# Create CogniteClient instance
os.environ["COGNITE_CLIENT_ID"] = client_id
os.environ["COGNITE_CLIENT_SECRET"] = client_secret
os.environ["COGNITE_PROJECT"] = project
os.environ["COGNITE_BASE_URL"] = f"https://{cluster}.cognitedata.com"
client = CogniteClient(client_name=client_name)
# Get all assets
assets = client.assets.list(limit=None)
if assets:
# Convert assets to dataframe
assets_data = []
for asset in assets:
asset_dict = {
"id": asset.id,
"name": asset.name,
"description": asset.description,
"external_id": asset.external_id,
"parent_id": asset.parent_id,
"created_time": asset.created_time,
"last_updated_time": asset.last_updated_time,
"root_id": asset.root_id,
"metadata": str(asset.metadata) if asset.metadata else None
}
assets_data.append(asset_dict)
df = pd.DataFrame(assets_data)
# Display total count
st.success(f"Successfully retrieved {len(assets)} assets")
# Search functionality
search_term = st.text_input("Search assets by name")
if search_term:
df = df[df['name'].str.contains(search_term, case=False, na=False)]
# Display assets table
st.dataframe(
df,
use_container_width=True,
column_config={
"id": st.column_config.NumberColumn("ID"),
"name": st.column_config.TextColumn("Name"),
"description": st.column_config.TextColumn("Description"),
"external_id": st.column_config.TextColumn("External ID"),
"parent_id": st.column_config.NumberColumn("Parent ID"),
"created_time": st.column_config.DatetimeColumn("Created Time"),
"last_updated_time": st.column_config.DatetimeColumn("Last Updated"),
"root_id": st.column_config.NumberColumn("Root ID"),
"metadata": st.column_config.TextColumn("Metadata")
}
)
else:
st.warning("No assets found in the project")
except Exception as e:
st.error(f"Error connecting to CDF: {str(e)}")
else:
st.info("Please enter your CDF credentials in the sidebar and click 'Connect to CDF' to view assets.")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?