如何使用Python下载.mstr格式的Microstrategy Dossiers
解决Python下载Microstrategy Dossiers为.mstr格式的思路
1. 自动获取Instance ID
Instance ID是文档实例化后的唯一标识,无需手动查找,通过mstrio的API可以自动生成:
- 先通过
Document类实例化目标文档,再调用create()方法生成实例,之后直接从文档对象中提取instance_id属性。 - 示例代码:
from mstrio.project_objects import Document from mstrio.connection import Connection # 建立与MicroStrategy的连接 conn = Connection(base_url="你的MSTR服务器地址", username="用户名", password="密码", project_name="项目名称") # 获取目标文档对象 doc = Document(connection=conn, id="你的文档ID") # 实例化文档,生成instance_id doc.create() # 提取instance_id instance_id = doc.instance_id
2. 构造export_document_to_mstr的body参数
body参数核心是指定导出格式为.mstr,基础结构如下,可根据需求添加筛选器等扩展字段:
export_body = { "formatType": "MSTR", "exportFlags": 0, # 0为默认导出配置,可根据需求调整参数值 "instanceId": instance_id }
3. 执行导出并保存文件
拿到instance_id和body参数后,调用导出方法并写入本地文件:
# 调用导出接口,获取.mstr格式的二进制内容 mstr_file_content = doc.export_document_to_mstr(body=export_body) # 将内容写入本地文件 with open("导出的 dossier.mstr", "wb") as f: f.write(mstr_file_content)
4. 替代方案:直接调用MicroStrategy REST API
如果mstrio库的封装方法仍有问题,可直接用requests调用原生REST API:
- 步骤:先创建文档实例获取instance_id,再发起导出请求
- 示例代码(需先通过登录接口获取认证token):
import requests base_url = "你的MSTR服务器地址" document_id = "你的文档ID" auth_token = "你的认证token" project_id = "你的项目ID" # 第一步:创建文档实例,获取instance_id instance_res = requests.post( f"{base_url}/api/v2/documents/{document_id}/instances", headers={"X-MSTR-AuthToken": auth_token, "X-MSTR-ProjectID": project_id} ) instance_id = instance_res.json()["id"] # 第二步:发起导出请求 export_res = requests.post( f"{base_url}/api/v2/documents/{document_id}/instances/{instance_id}/exports", headers={"X-MSTR-AuthToken": auth_token, "X-MSTR-ProjectID": project_id}, json={"formatType": "MSTR"} ) # 保存导出文件 with open("dossier_export.mstr", "wb") as f: f.write(export_res.content)
关键注意事项
- 确保你的账号拥有目标文档的导出权限
- 建议使用最新版mstrio库,避免API兼容性问题
- 若出现失败,优先查看API响应的错误信息,针对性排查权限或参数问题
内容的提问来源于stack exchange,提问作者Semih
相关产品推荐
相关产品推荐

