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

如何用Python筛选Power BI服务仪表盘?解决EmbedMode报错问题

问题解决:修复pyexpat.model报错并实现仪表盘批量筛选设置

一、修复module 'pyexpat.model' has no attribute 'EmbedMode'报错

这个错误是因为导入路径错误:你误引用了Python内置XML解析库pyexpat的model模块,而非powerbiclient官方提供的模型类。

修正步骤

  1. 替换错误的导入语句,明确从powerbiclient.models导入所需类:
from powerbiclient.models import EmbedMode, Permissions
  1. 重新实例化Report对象:
report_edit = Report(
    group_id=group_id, 
    report_id=report_id, 
    auth=auth, 
    view_mode=EmbedMode.EDIT.value, 
    permissions=Permissions.READWRITE.value
)

二、为克隆的仪表盘设置个性化筛选

注意:Power BI仪表盘的筛选依赖底层磁贴配置,powerbiclient更聚焦报表嵌入交互,批量操作仪表盘筛选推荐使用Power BI REST API,以下提供两种可行方案:

方案1:逐个更新仪表盘磁贴的筛选条件

适合需要对每个仪表盘设置独立静态筛选的场景,结合你现有克隆代码修改:

# 【在克隆仪表盘的循环内添加以下代码】
# 1. 获取克隆后的仪表盘ID(从克隆接口返回结果中提取)
result_clone_dashboard = clone_dashboard.json()
dashboard_id = result_clone_dashboard['id']
dashboard_link = result_clone_dashboard['webUrl']

# 2. 获取当前仪表盘的所有磁贴
tiles_endpoint = f"https://api.powerbi.com/v1.0/myorg/groups/{group_id}/dashboards/{dashboard_id}/tiles"
get_tiles = requests.get(tiles_endpoint, headers=headers)
if get_tiles.status_code != 200:
    print(f"获取磁贴失败: {get_tiles.status_code}")
    continue
tiles = get_tiles.json()['value']

# 3. 批量更新磁贴筛选(替换为你的数据集、表、筛选列信息)
dataset_id = "你的数据集ID"
target_table = "业务数据表"
filter_column = "用户ID"

for tile in tiles:
    tile_id = tile['id']
    # 构建筛选规则:筛选当前用户ID对应的数据
    filter_payload = {
        "datasetId": dataset_id,
        "filters": [
            {
                "filterType": "Basic",
                "target": {"table": target_table, "column": filter_column},
                "operator": "Equals",
                "values": [cell_value]
            }
        ]
    }
    # 发送更新请求
    update_tile_endpoint = f"https://api.powerbi.com/v1.0/myorg/groups/{group_id}/dashboards/{dashboard_id}/tiles/{tile_id}"
    update_response = requests.patch(update_tile_endpoint, json=filter_payload, headers=headers)
    if update_response.status_code != 200:
        print(f"更新磁贴{tile_id}失败: {update_response.status_code}")

方案2:使用行级别安全(RLS)实现自动筛选

适合用户数据权限隔离的场景,无需逐个修改磁贴,效率更高:

  1. 先在Power BI数据集上配置RLS角色(比如创建UserRole,筛选规则为用户ID = USERPRINCIPALNAME()或对应字段)
  2. 在克隆仪表盘的循环内,给当前用户分配RLS角色:
# 【在克隆仪表盘的循环内添加以下代码】
dataset_id = "你的数据集ID"
rls_role_name = "UserRole"

# 给用户分配RLS角色
rls_assign_endpoint = f"https://api.powerbi.com/v1.0/myorg/groups/{group_id}/datasets/{dataset_id}/roles/{rls_role_name}/members"
rls_payload = {
    "identifier": cell_value,
    "principalType": "User"
}
assign_response = requests.post(rls_assign_endpoint, json=rls_payload, headers=headers)
if assign_response.status_code != 201:
    print(f"为用户{cell_value}分配RLS角色失败: {assign_response.status_code}")

用户访问自己的仪表盘时,会自动应用RLS规则,仅看到对应权限的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:17:52