首页 后端开发 Python教程 Personalize for each user with Streamlit in Snowflake (SiS)

Personalize for each user with Streamlit in Snowflake (SiS)

Sep 14, 2024 pm 12:15 PM

Introduction

At the end of July 2024, Current_User and Row Access Policy became available in Streamlit in Snowflake.

The exciting part of this update is that it's now easy and secure to identify the Snowflake user connected to the application and customize processing for each user.

Without needing to set up a custom login mechanism or user management table, you can personalize a single application for each user in ways like:

  • Changing the application display for each user
  • Preparing personalized analysis dashboards for each user
  • Using row access policies to get different query output results for each user (Enterprise Edition and above)

In this post, we'll create a simple ToDo list that displays individual user information.

Note: This post represents my personal views and not those of Snowflake.

Feature Overview

Goals

  • Manage personal ToDo lists using a single shared app
  • Use row access policy to prevent other people's ToDos from being displayed

Completed Image

Personalize for each user with Streamlit in Snowflake (SiS)
User TKANNO's screen

Personalize for each user with Streamlit in Snowflake (SiS)
User TARO's screen

Prerequisites

  • Snowflake account
    • Enterprise Edition account is required to use row access policy

Note

  • Streamlit in Snowflake runs with owner privileges, so Current_Role will be the same as the Streamlit in Snowflake application role. (Therefore, it cannot be used for personalization)

Procedure

Create a table to store the ToDo list

Execute the following command from a worksheet:

-- Create ToDo list table
CREATE TABLE IF NOT EXISTS todo_list (
    id INT AUTOINCREMENT,
    task VARCHAR(255),
    status VARCHAR(20),
    due_date DATE,
    completed_date DATE,
    owner VARCHAR(50)
);

Create a row access policy

This policy returns rows where the owner in the todo_list table matches the current_user connected to the Streamlit in Snowflake application.

Execute the following command from the worksheet:

-- Create row access policy
CREATE ROW ACCESS POLICY IF NOT EXISTS todo_row_access_policy
    AS (owner VARCHAR) RETURNS BOOLEAN ->
        owner = CURRENT_USER();

Apply the row access policy

Execute the following command from the worksheet:

-- Apply row access policy
ALTER TABLE todo_list ADD ROW ACCESS POLICY todo_row_access_policy ON (owner);

This completes the worksheet operations.

Run the Streamlit in Snowflake app

Create a new Streamlit in Snowflake app and copy & paste the following code:

Line 14 is where the current user connected to the app is retrieved as a string.

import streamlit as st
from snowflake.snowpark.context import get_active_session
import pandas as pd

# Layout settings
st.set_page_config(
    layout="wide"
)

# Get Snowflake session
session = get_active_session()

# Get current user
current_user = session.sql("SELECT CURRENT_USER()").collect()[0][0]

# Get ToDo list
def get_todo_list():
    return session.table("todo_list").to_pandas()

# Add or update task
def upsert_task(task_id, task, status, due_date, completed_date):
    due_date_sql = f"'{due_date}'" if due_date else "NULL"
    completed_date_sql = f"'{completed_date}'" if completed_date else "NULL"

    if task_id:
        session.sql(f"""
        UPDATE todo_list
        SET task = '{task}', status = '{status}', due_date = {due_date_sql}, completed_date = {completed_date_sql}
        WHERE id = {task_id}
        """).collect()
    else:
        session.sql(f"""
        INSERT INTO todo_list (task, status, owner, due_date, completed_date)
        VALUES ('{task}', '{status}', '{current_user}', {due_date_sql}, {completed_date_sql})
        """).collect()

# Delete task
def delete_task(task_id):
    session.sql(f"DELETE FROM todo_list WHERE id = {task_id}").collect()

# Main function
def main():
    st.title(f"{current_user}'s Personal Dashboard")

    # Task list
    st.subheader(f"{current_user}'s ToDo List")
    todo_df = get_todo_list()

    # Display header
    col1, col2, col3, col4, col5 = st.columns([3, 2, 2, 2, 2])
    col1.write("Task")
    col2.write("Status")
    col3.write("Due Date")
    col4.write("Completed Date")
    col5.write("Delete")

    # Display task list
    for _, row in todo_df.iterrows():
        col1, col2, col3, col4, col5 = st.columns([3, 2, 2, 2, 2])

        with col1:
            task = st.text_input("task", value=row['TASK'], key=f"task_{row['ID']}", label_visibility="collapsed")

        with col2:
            status = st.selectbox("status", ["Pending", "In Progress", "Completed"], index=["Pending", "In Progress", "Completed"].index(row['STATUS']), key=f"status_{row['ID']}", label_visibility="collapsed")

        with col3:
            due_date = st.date_input("due_date", value=pd.to_datetime(row['DUE_DATE']).date() if pd.notna(row['DUE_DATE']) else None, key=f"due_date_{row['ID']}", label_visibility="collapsed")

        with col4:
            completed_date = st.date_input("comp_date", value=pd.to_datetime(row['COMPLETED_DATE']).date() if pd.notna(row['COMPLETED_DATE']) else None, key=f"completed_date_{row['ID']}", label_visibility="collapsed")

        with col5:
            if st.button("Delete", key=f"delete_{row['ID']}"):
                delete_task(row['ID'])
                st.experimental_rerun()

        # Update database immediately if values change
        if task != row['TASK'] or status != row['STATUS'] or due_date != row['DUE_DATE'] or completed_date != row['COMPLETED_DATE']:
            upsert_task(row['ID'], task, status, due_date, completed_date)
            st.experimental_rerun()

    # Add new task
    st.subheader("Add New Task")
    new_task = st.text_input("New Task")
    new_status = st.selectbox("Status", ["Pending", "In Progress", "Completed"])
    new_due_date = st.date_input("Due Date")
    if st.button("Add"):
        upsert_task(None, new_task, new_status, new_due_date, None)
        st.success("New task added")
        st.experimental_rerun()

# Main process
if __name__ == "__main__":
    main()

Conclusion

What do you think? By combining Current_User and row access policy, you can create a secure application personalized for each user with simple steps. This opens up possibilities for creating even more user-friendly applications based on your ideas.

Some advanced ideas include adding Current_User information as a signature when writing to tables via Streamlit in Snowflake, or using personalized information as context for Cortex LLM to create a personal assistant.

Please try challenging yourself with interesting uses of Current_User!

Announcements

Snowflake What's New Updates on X

I'm sharing Snowflake's What's New updates on X. Please feel free to follow if you're interested!

English Version

Snowflake What's New Bot (English Version)
https://x.com/snow_new_en

Japanese Version

Snowflake What's New Bot (Japanese Version)
https://x.com/snow_new_jp

Change History

(20240914) Initial post

Original Japanese Article

https://zenn.dev/tsubasa_tech/articles/a23029dfe97c46

以上是Personalize for each user with Streamlit in Snowflake (SiS)的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Python类中的多态性 Python类中的多态性 Jul 05, 2025 am 02:58 AM

多态是Python面向对象编程中的核心概念,指“一种接口,多种实现”,允许统一处理不同类型的对象。1.多态通过方法重写实现,子类可重新定义父类方法,如Animal类的speak()方法在Dog和Cat子类中有不同实现。2.多态的实际用途包括简化代码结构、增强可扩展性,例如图形绘制程序中统一调用draw()方法,或游戏开发中处理不同角色的共同行为。3.Python实现多态需满足:父类定义方法,子类重写该方法,但不要求继承同一父类,只要对象实现相同方法即可,这称为“鸭子类型”。4.注意事项包括保持方

Python函数参数和参数 Python函数参数和参数 Jul 04, 2025 am 03:26 AM

参数(parameters)是定义函数时的占位符,而传参(arguments)是调用时传入的具体值。1.位置参数需按顺序传递,顺序错误会导致结果错误;2.关键字参数通过参数名指定,可改变顺序且提高可读性;3.默认参数值在定义时赋值,避免重复代码,但应避免使用可变对象作为默认值;4.args和*kwargs可处理不定数量的参数,适用于通用接口或装饰器,但应谨慎使用以保持可读性。

python`@classmethod'装饰师解释了 python`@classmethod'装饰师解释了 Jul 04, 2025 am 03:26 AM

类方法是Python中通过@classmethod装饰器定义的方法,其第一个参数为类本身(cls),用于访问或修改类状态。它可通过类或实例调用,影响的是整个类而非特定实例;例如在Person类中,show_count()方法统计创建的对象数量;定义类方法时需使用@classmethod装饰器并将首参命名为cls,如change_var(new_value)方法可修改类变量;类方法与实例方法(self参数)、静态方法(无自动参数)不同,适用于工厂方法、替代构造函数及管理类变量等场景;常见用途包括从

什么是python的列表切片? 什么是python的列表切片? Jun 29, 2025 am 02:15 AM

ListslicinginPythonextractsaportionofalistusingindices.1.Itusesthesyntaxlist[start:end:step],wherestartisinclusive,endisexclusive,andstepdefinestheinterval.2.Ifstartorendareomitted,Pythondefaultstothebeginningorendofthelist.3.Commonusesincludegetting

解释Python发电机和迭代器。 解释Python发电机和迭代器。 Jul 05, 2025 am 02:55 AM

迭代器是实现__iter__()和__next__()方法的对象,生成器是简化版的迭代器,通过yield关键字自动实现这些方法。1.迭代器每次调用next()返回一个元素,无更多元素时抛出StopIteration异常。2.生成器通过函数定义,使用yield按需生成数据,节省内存且支持无限序列。3.处理已有集合时用迭代器,动态生成大数据或需惰性求值时用生成器,如读取大文件时逐行加载。注意:列表等可迭代对象不是迭代器,迭代器到尽头后需重新创建,生成器只能遍历一次。

如何在Python中结合两个列表? 如何在Python中结合两个列表? Jun 30, 2025 am 02:04 AM

合并两个列表有多种方法,选择合适方式可提升效率。1.使用 号拼接生成新列表,如list1 list2;2.使用 =修改原列表,如list1 =list2;3.使用extend()方法在原列表上操作,如list1.extend(list2);4.使用号解包合并(Python3.5 ),如[list1,*list2],支持灵活组合多个列表或添加元素。不同方法适用于不同场景,需根据是否修改原列表及Python版本进行选择。

如何处理Python中的API身份验证 如何处理Python中的API身份验证 Jul 13, 2025 am 02:22 AM

处理API认证的关键在于理解并正确使用认证方式。1.APIKey是最简单的认证方式,通常放在请求头或URL参数中;2.BasicAuth使用用户名和密码进行Base64编码传输,适合内部系统;3.OAuth2需先通过client_id和client_secret获取Token,再在请求头中带上BearerToken;4.为应对Token过期,可封装Token管理类自动刷新Token;总之,根据文档选择合适方式,并安全存储密钥信息是关键。

什么是python魔法方法或dunder方法? 什么是python魔法方法或dunder方法? Jul 04, 2025 am 03:20 AM

Python的magicmethods(或称dunder方法)是用于定义对象行为的特殊方法,它们以双下划线开头和结尾。1.它们使对象能够响应内置操作,如加法、比较、字符串表示等;2.常见用例包括对象初始化与表示(__init__、__repr__、__str__)、算术运算(__add__、__sub__、__mul__)及比较运算(__eq__、__lt__);3.使用时应确保其行为符合预期,例如__repr__应返回可重构对象的表达式,算术方法应返回新实例;4.应避免过度使用或以令人困惑的方

See all articles