Python上传Pandas生成的CSV至SharePoint时遇认证错误求助
问题重现
尝试将Pandas DataFrame生成的CSV文件上传至SharePoint/OneDrive,执行代码时触发以下错误:
ValueError: 无法从https://login.microsoftonline.com/extSTS.srf获取二进制安全令牌
用户提供的测试代码:
import pandas as pd from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.authentication_context import AuthenticationContext df = pd.DataFrame() site_url = "https://{tenant id: str = ########-####-####-####-############ ???}.sharepoint.com/sites/{site name: str = 'tktktk' ???}" username = "{user}@{site name}.com" password = "{tktktk}" auth_ctx = AuthenticationContext(site_url) auth_ctx.acquire_token_for_user(username, password) ctx = ClientContext(site_url, auth_ctx) web = ctx.web ctx.load(web) try: ctx.execute_query() print(f"Connection to SharePoint site '{web.properties['Title']}' successful!") except Exception as e: print(f"Error connecting to SharePoint: {e}")
错误原因分析
- 配置信息格式错误:
site_url、username中混入了占位符语法(如{tenant id:...}),需替换为实际有效的站点URL和账号信息 - 认证方式不兼容:若账号开启了多因素认证(MFA),普通密码无法通过
acquire_token_for_user获取令牌 - 库版本或租户限制:旧版本
office365-rest-python-client可能存在认证适配问题,部分租户启用现代认证后会限制传统密码流
解决方案
方案1:无MFA场景的修正代码
先替换占位符为真实配置,再执行认证与上传操作:
import pandas as pd from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.authentication_context import AuthenticationContext # 替换为实际有效信息 site_url = "https://你的租户名.sharepoint.com/sites/你的站点名" username = "你的完整工作账号@租户域名.com" password = "你的账号密码(若开启MFA需用应用密码)" # 初始化认证上下文 auth_ctx = AuthenticationContext(site_url) if auth_ctx.acquire_token_for_user(username, password): ctx = ClientContext(site_url, auth_ctx) web = ctx.web ctx.load(web) try: ctx.execute_query() print(f"成功连接到SharePoint站点: {web.properties['Title']}") # 生成CSV并上传到默认文档库 df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]}) csv_content = df.to_csv(index=False).encode('utf-8') target_folder = ctx.web.get_folder_by_server_relative_url("Shared Documents") target_file = target_folder.upload_file("uploaded_data.csv", csv_content) ctx.execute_query() print(f"CSV文件已上传至: {target_file.serverRelativeUrl}") except Exception as e: print(f"执行请求出错: {e}") else: print(f"认证失败: {auth_ctx.get_last_error()}")
方案2:MFA场景的交互式认证(推荐)
若账号开启MFA,使用设备码认证方式,需先安装依赖库:
pip install azure-identity office365-rest-python-client pandas
代码示例:
import pandas as pd from office365.sharepoint.client_context import ClientContext from azure.identity import DeviceCodeCredential # 替换为实际配置 site_url = "https://你的租户名.sharepoint.com/sites/你的站点名" client_id = "你的Azure AD应用客户端ID" # 需在Azure AD注册应用并授予SharePoint读写权限 # 初始化设备码认证 credential = DeviceCodeCredential(client_id=client_id) ctx = ClientContext(site_url).with_credentials(credential) try: web = ctx.web ctx.load(web) ctx.execute_query() print(f"成功连接到SharePoint站点: {web.properties['Title']}") # 生成并上传CSV df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]}) csv_content = df.to_csv(index=False).encode('utf-8') target_folder = ctx.web.get_folder_by_server_relative_url("Shared Documents") target_file = target_folder.upload_file("uploaded_data_mfa.csv", csv_content) ctx.execute_query() print(f"CSV文件已上传至: {target_file.serverRelativeUrl}") except Exception as e: print(f"出错: {e}")
关键注意事项
- 确保
office365-rest-python-client为最新版本:pip install --upgrade office365-rest-python-client - 使用客户端凭证认证时,需在Azure AD中注册应用并授予
Sites.ReadWrite.All权限 - 文档库相对路径需与实际一致,自定义库替换为对应名称即可
内容的提问来源于stack exchange,提问作者OJT
相关产品推荐
相关产品推荐

