You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python上传文件至SharePoint遇问题:403错误及模块导入失败

一、使用requests Basic Authentication上传出现403 Forbidden的解决方案

问题根源

  • SharePoint Online已逐步淘汰Basic Authentication,默认禁用该认证方式,需使用OAuth2.0/现代认证。
  • 上传URL错误:你使用的document_library_url是网页展示地址(AllItems.aspx),并非文档库的API上传端点。

修正方案

改用msal库获取OAuth令牌完成认证,同时修正上传URL:

import requests
import msal

# 配置参数
tenant_id = "你的租户ID"
client_id = "Azure AD应用注册ID"
username = config['sharepoint_cred']['username']
password = config['sharepoint_cred']['password']
sharepoint_url = "https://something.sharepoint.com/sites/something"
local_file_path = "my_plot.png"
file_name = "my_plot.png"
document_library = "Shared Documents"

# 获取访问令牌
authority = f"https://login.microsoftonline.com/{tenant_id}"
scope = [f"{sharepoint_url}/.default"]

app = msal.PublicClientApplication(client_id, authority=authority)
result = app.acquire_token_by_username_password(username, password, scopes=scope)

if "access_token" in result:
    headers = {
        "Authorization": f"Bearer {result['access_token']}",
        "Content-Type": "image/png"
    }
    # 构建正确的上传API路径
    upload_url = f"{sharepoint_url}/_api/web/GetFolderByServerRelativeUrl('{document_library}')/files/add(overwrite=true,url='{file_name}')"
    with open(local_file_path, "rb") as f:
        response = requests.post(upload_url, headers=headers, data=f)
    
    if response.status_code in [200, 201]:
        print("文件上传成功")
    else:
        print(f"上传失败,响应内容:{response.text}")
else:
    print(f"令牌获取失败:{result.get('error_description')}")

注意:需先在Azure AD注册应用,授予Files.ReadWrite.All权限,且账号拥有文档库上传权限。


二、Office365-REST-Python-Client导入FileCreationInformation失败的解决方案

问题根源

库版本更新后,FileCreationInformation的导入路径被调整,旧写法已废弃。

修正方案

  1. 先升级至最新版本库:
pip install --upgrade office365-rest-python-client
  1. 使用新版本兼容的上传代码:
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext

sharepoint_url = 'https://something.sharepoint.com/sites/something'
# 注意:指向文档库的相对路径,而非站点路径
document_library_relative_url = '/sites/something/Shared Documents'
username = config['sharepoint_cred']['username']
password = config['sharepoint_cred']['password']
local_file_path = 'my_plot.png'
file_name = 'my_plot.png'

# 认证并上传
ctx = ClientContext(sharepoint_url).with_credentials(UserCredential(username, password))
target_folder = ctx.web.get_folder_by_server_relative_url(document_library_relative_url)

# 简化的文件上传方法
with open(local_file_path, 'rb') as f:
    target_file = target_folder.upload_file(file_name, f).execute_query()
    print(f"文件已上传至:{target_file.serverRelativeUrl}")

注意:若账号启用了MFA,需改用设备码认证或应用权限认证,无法直接使用用户名密码登录。

内容的提问来源于stack exchange,提问作者Priya Srivatsa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 05:42:46