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

使用Python上传文件至SharePoint时遇AttributeError:NoneType无json属性

使用Office365-REST模块上传SharePoint文件时的AttributeError问题及解决

问题场景

尝试用Office365-REST模块向SharePoint上传文件,编写的Python代码如下:

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.creation_information import FileCreationInformation
import traceback

try:
    fullurl = 'https://org.sharepoint.com/sites/SiteName/'
    fileName = 'c:/temp/upload.zip'
    rootfolder = 'Documents'
    targetfolder = '/PythonTests/'

    ctx_auth = AuthenticationContext(url=fullurl)
    if  ctx_auth.acquire_token_for_app(client_id='redacted', client_secret='redacted'):
        ctx = ClientContext(fullurl, ctx_auth)
        target_list = ctx.web.lists.get_by_title(rootfolder)
        info = FileCreationInformation()
        with open(fileName, 'rb') as content_file:
            info.content = content = content_file.read()
        info.url = fileName
        info.overwrite = True
        upload_file = target_list.root_folder.files.add(fileName.split("/")[-1], info.content, overwrite=True)
        ctx.execute_query()
except:
    traceback.print_exc()

执行后触发错误:

Exception has occurred: AttributeError
'NoneType' object has no attribute 'json'
  File "C:\scripts\upload_to_sharepoint.py", line 20, in <module>
    ctx.execute_query()
AttributeError: 'NoneType' object has no attribute 'json'

错误栈详情

Traceback (most recent call last):
  File "C:\Code\Python\Office365-REST\upload_to_sharepoint.py", line 22, in <module>
    ctx.execute_query()
  File "C:\Python\Python38\lib\site-packages\office365\runtime\client_runtime_context.py", line 181, in execute_query
    self.pending_request().execute_query(qry)
  File "C:\Python\Python38\lib\site-packages\office365\runtime\client_request.py", line 58, in execute_query
    response = self.execute_request_direct(request)
  File "C:\Python\Python38\lib\site-packages\office365\runtime\client_request.py", line 70, in execute_request_direct
    self.beforeExecute.notify(request)
  File "C:\Python\Python38\lib\site-packages\office365\runtime\types\event_handler.py", line 21, in notify
    listener(*args, **kwargs)
  File "C:\Python\Python38\lib\site-packages\office365\sharepoint\client_context.py", line 221, in _build_modification_query     
    self._ensure_form_digest(request)
  File "C:\Python\Python38\lib\site-packages\office365\sharepoint\client_context.py", line 157, in _ensure_form_digest
    self._ctx_web_info = self._get_context_web_information()
  File "C:\Python\Python38\lib\site-packages\office365\sharepoint\client_context.py", line 170, in _get_context_web_information  
    client.map_json(response.json(), return_value, json_format)
AttributeError: 'NoneType' object has no attribute 'json'

已做排查

  • 发现向/contextInfo URL发送请求时,request.auth为None且无请求头,但AuthenticationContext显示已完成认证,也能成功获取target_list
  • 用Graph API Explorer测试:获取站点驱动器返回空列表,获取默认驱动器提示权限拒绝,怀疑权限不足
  • 更新API版本并调整代码(如下),仍触发相同错误:
import os

from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.client_credential import ClientCredential


def print_upload_progress(offset):
    file_size = os.path.getsize(local_path)
    print("Uploaded '{0}' bytes from '{1}'...[{2}%]".format(offset, file_size, round(offset / file_size * 100, 2)))


ctx = ClientContext('https://org.sharepoint.com/sites/SiteName/').with_credentials(ClientCredential(client_id='redacted', client_secret='redacted'))

target_url = "Shared Documents/PythonTests"
target_folder = ctx.web.get_folder_by_server_relative_url(target_url)
size_chunk = 1000000
local_path = "c:/temp/upload.zip"
with open(local_path, 'rb') as f:
    uploaded_file = target_folder.files.create_upload_session(f, size_chunk,
                                                              print_upload_progress).execute_query()

print('File {0} has been uploaded successfully'.format(uploaded_file.serverRelativeUrl))

错误栈与之前一致

  • 在不同SharePoint站点(含Teams创建的站点)复现问题,排除站点结构影响

替代解决方案:PowerShell脚本

绕过Office365-REST模块,使用PowerShell实现文件上传:

# 配置参数
$siteUrl = "https://org.sharepoint.com/sites/SiteName/"
$clientId = "你的客户端ID"
$clientSecret = "你的客户端密钥"
$localFilePath = "C:\temp\upload.zip"
$targetFolderUrl = "Shared Documents/PythonTests"

# 加载SharePoint PnP模块(需提前安装:Install-Module -Name PnP.PowerShell)
Import-Module PnP.PowerShell

# 连接到SharePoint站点
Connect-PnPOnline -Url $siteUrl -ClientId $clientId -ClientSecret $clientSecret

# 上传文件
Add-PnPFile -Path $localFilePath -Folder $targetFolderUrl -OverwriteIfExists

# 断开连接
Disconnect-PnPOnline

注意事项

  1. 确保已安装PnP.PowerShell模块,若未安装需先执行Install-Module -Name PnP.PowerShell(需管理员权限)
  2. 确认Azure AD应用已授予SharePoint相关权限(如Sites.FullControl.All或Sites.Manage.All),并已在目标站点上授予应用访问权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:40:02