如何在Databricks笔记本中获取workspaceUrl与clusterOwnerUserId以生成下载链接?
在Databricks笔记本中获取workspaceUrl和clusterOwnerUserId参数的方法
要生成Databricks FileStore的下载链接,可通过dbutils提供的Notebook Context API直接获取所需参数:
- workspaceUrl:工作区的域名地址,从Notebook Context的
apiUrl属性提取 - clusterOwnerUserId:对应下载链接中的
o参数,实际为工作区的组织ID(Org ID),从Context标签中获取
完整代码示例
# 获取workspaceUrl和clusterOwnerUserId(即工作区Org ID) context = dbutils.notebook.entry_point.getDbutils().notebook().getContext() # 提取workspaceUrl,移除默认的https://前缀 workspaceUrl = context.apiUrl().get().replace("https://", "") # 提取clusterOwnerUserId(下载链接的o参数对应Org ID) clusterOwnerUserId = context.tags().get("orgId").get() tmp_file = '/tmp/output_abcd.xlsx' filestore_file = '/FileStore/output_abcd.xlsx' # 生成文件的逻辑(省略)... dbutils.fs.cp(f'file:{tmp_file}', filestore_file) downloadUrl = f'https://{workspaceUrl}/files/output_abcd.xlsx?o={clusterOwnerUserId}' displayHTML(f"<a href='{downloadUrl}'>download</a>")
补充说明
apiUrl()返回的是带https://前缀的完整工作区地址,因此需要用replace移除前缀,避免下载链接出现重复的协议头- 若你实际需要的是集群所有者的用户ID而非工作区Org ID,可替换为
context.tags().get("user").get(),但注意下载链接的o参数通常要求填写Org ID,而非用户ID
内容的提问来源于stack exchange,提问作者Chris Snow
相关产品推荐
相关产品推荐

