You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SQL来源的Pandas DataFrame转为Streamlit Authenticator凭据字典

将SQL获取的Pandas DataFrame转换为Streamlit Authenticator凭据字典

需求说明

需要把从SQL数据库查询得到的Pandas DataFrame,转换成Streamlit Authenticator要求的嵌套字典格式。SQL查询已将字段映射为目标格式所需的列名:usernames(用户名)、name(用户姓名)、password(哈希密码)。

实现步骤

1. 从SQL读取数据到DataFrame

先通过SQL查询获取符合要求的数据,示例代码需替换为你的数据库连接信息:

import pandas as pd
from sqlalchemy import create_engine

# 替换为你的数据库连接字符串
db_conn_str = "your_database_connection_string"
engine = create_engine(db_conn_str)

# 执行指定SQL查询
sql_query = """SELECT username as usernames,nome as name,HashPython as password FROM AspNetUsers WHERE HashPython is not null"""
user_df = pd.read_sql(sql_query, engine)

2. 转换为目标凭据字典

通过Pandas的iterrows()遍历DataFrame,用字典推导式直接生成符合要求的凭据结构:

credentials = {
    "usernames": {
        row["usernames"]: {
            "name": row["name"],
            "password": row["password"]
        } for _, row in user_df.iterrows()
    }
}

可选校验处理

为避免无效数据引发问题,可提前过滤关键字段为空的记录:

# 过滤掉用户名或姓名为空的行
user_df = user_df.dropna(subset=["usernames", "name"])

格式验证

转换后的credentials结构完全匹配Streamlit Authenticator要求,示例如下:

{
    "usernames": {
        "user@inv.com": {
            "name": "user1",
            "password": "已生成的哈希密码"
        },
        "another_user@example.com": {
            "name": "Another User",
            "password": "另一哈希密码"
        }
    }
}

内容的提问来源于stack exchange,提问作者Felisberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:28:12