快速入门:运行第一个 DAX 查询

在本快速入门中,你将对Power BI进行身份验证,针对语义模型执行 DAX 查询,并将箭头响应反序列化为本地数据结构。

先决条件

  • 具有至少一个语义模型的Power BI工作区。
  • 语义模型的创建和 读取 权限。
  • Microsoft Entra应用注册(或使用交互式身份验证进行测试)。
  • Python 3.10 或更高版本。

  • 安装依赖项:

    pip install msal pyarrow pandas
    

1 - 身份验证

获取带有 https://analysis.windows.net/powerbi/api/.default 特定作用域的 Bearer 令牌。

from msal import PublicClientApplication

client_id = "YOUR_APP_CLIENT_ID"
authority = "https://login.microsoftonline.com/YOUR_TENANT_ID"
scopes = ["https://analysis.windows.net/powerbi/api/.default"]

app = PublicClientApplication(client_id, authority=authority)
result = app.acquire_token_interactive(scopes=scopes)

access_token = result["access_token"]

2 - 执行 DAX 查询

使用简单 EVALUATE 语句将 POST 请求发送到执行查询箭头终结点。

import io
import pyarrow as pa
import requests

group_id = "YOUR_WORKSPACE_ID"
dataset_id = "YOUR_DATASET_ID"

url = (f"https://api.powerbi.com/v1.0/myorg/groups/{group_id}"
       f"/datasets/{dataset_id}/executeDaxQueries")

headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json",
}

body = {"query": "EVALUATE TOPN(5, 'DimProduct')"}

response = requests.post(url, headers=headers, json=body)
response.raise_for_status()

reader = pa.ipc.open_stream(io.BytesIO(response.content))
table = reader.read_all()
df = table.to_pandas()

print(df)

3 - 检查结果

# Print the Arrow schema (column names and types)
print(table.schema)

# Show the first few rows as a pandas DataFrame
print(df.head())

# Access a specific column
print(table.column("ProductName").to_pylist()[:5])

清理资源

如果只创建用于测试的Microsoft Entra应用注册,请导航到 Azure 门户并将其删除。 访问令牌自动过期,不需要手动吊销。