使用Python脚本上传文件至SharePoint时遇连接重置错误求助
已按步骤创建Azure AD应用,获取了site-id、drive-id,使用脚本上传文件到SharePoint Online时,持续报错:
requests.exceptions.connectionError: ('Connection aborted.', ConnectionResetError(10054, 'An Existing connection was focibly closed by the remote host', None, 10054, None))
用户使用的脚本代码:
import os import requests # Azure AD app registration credentials client_id = '376f340a-7b96-40c6-89fb-xxxxxxxxx' client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxx' tenant_id = '3f5c7a77-062d-426c-8582-1xxxxxxxxxxx' # SharePoint Online site URL and library name site_id = '6d4d4ae7-be11-47d0-a9ad-xxxxxxxxxxx' library_name = 'sridoclib' drive_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Authenticate and get an access token auth_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token' data = { 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret, 'scope': 'https://graph.microsoft.com/.default' } response = requests.post(auth_url, data=data) access_token = response.json()['access_token'] # Upload a file to the SharePoint document library using the Microsoft Graph API file_path = 'C:/Users/sridevi/Desktop/test.txt' #local file path file_name = 'test.txt' folder_name = 'sri' upload_url = f'https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{drive_id}/items/root:/{folder_name}/{file_name}:/content' headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/octet-stream', 'Content-Length': str(os.path.getsize(file_path)) }
可能的原因及解决方法
1. 网络环境限制(最常见)
- 公司防火墙、代理服务器拦截了Graph API请求,或网络不稳定导致连接被强制断开。
- 解决:
- 切换到非公司网络(如手机热点)测试,验证是否为网络限制问题。
- 若需使用公司网络,联系IT部门确认开放
https://graph.microsoft.com和https://login.microsoftonline.com的HTTPS(443端口)访问权限。 - 脚本中添加代理配置(如果公司要求):
proxies = { 'http': 'http://your-proxy:port', 'https': 'http://your-proxy:port' } # 认证和上传请求都需加入proxies参数 response = requests.post(auth_url, data=data, proxies=proxies) with open(file_path, 'rb') as f: upload_response = requests.put(upload_url, headers=headers, data=f, proxies=proxies)
2. 请求代码缺失或请求头错误
- 脚本仅定义了上传URL和请求头,但未发起实际的上传请求;手动设置
Content-Length可能导致与实际文件大小不匹配,触发服务器断开连接。 - 解决:
- 补充上传请求代码,并移除手动设置的
Content-Length(requests会自动处理该字段):# 修正请求头 headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/octet-stream' } # 发起上传请求 with open(file_path, 'rb') as f: upload_response = requests.put(upload_url, headers=headers, data=f) # 打印响应信息排查问题 print(upload_response.status_code) print(upload_response.text)
- 补充上传请求代码,并移除手动设置的
3. Azure应用权限配置不全
- 虽创建了应用,但未授予足够的Graph API应用权限,或未完成管理员同意。
- 解决:
- 登录Azure门户,进入应用注册 → 权限管理 → 添加权限 → Microsoft Graph → 应用权限,添加
Files.ReadWrite.All或Sites.ReadWrite.All。 - 点击「授予管理员同意」(需租户管理员权限)。
- 登录Azure门户,进入应用注册 → 权限管理 → 添加权限 → Microsoft Graph → 应用权限,添加
4. 目标路径或ID错误
- site-id、drive-id或文件夹名称
folder_name填写错误,导致请求路径无效,服务器强制断开连接。 - 解决:
- 使用Graph Explorer验证ID正确性:访问
https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{drive_id},返回正常数据则ID有效。 - 验证文件夹存在性:访问
https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{drive_id}/items/root:/{folder_name},返回404则需创建文件夹或修正名称。
- 使用Graph Explorer验证ID正确性:访问
5. 缺少超时与重试机制
- 网络波动导致请求超时,无重试逻辑直接触发报错。
- 解决:
- 为requests添加超时参数和重试机制:
from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry # 创建带重试的session session = requests.Session() retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504]) adapter = HTTPAdapter(max_retries=retry) session.mount('https://', adapter) # 使用session发送请求 response = session.post(auth_url, data=data) with open(file_path, 'rb') as f: upload_response = session.put(upload_url, headers=headers, data=f, timeout=30)
- 为requests添加超时参数和重试机制:
内容的提问来源于stack exchange,提问作者Newbietech
相关产品推荐
相关产品推荐

