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

Python连接SharePoint报NameError及ClientContext未定义问题

问题根因

你遇到的两个报错分别由两个独立的低级错误导致:

  • 编辑器提示client context is undefined:代码只导入了UserCredential类,没有导入ClientContext类,Python解释器无法识别ClientContext这个标识符。你运行函数定义时没有触发报错,是因为Python只有在执行到对应代码行时才会校验名称是否存在,定义函数阶段不会执行函数内部代码。
  • 运行时抛出NameError: name 'get_sharepoint_context_using_app' is not defined:你实际定义的函数名为get_sharepoint_context_using_user(),但后续调用时写的是不存在的get_sharepoint_context_using_app(),函数名拼写/匹配错误。
修复方法
  1. 在代码开头补充ClientContext的导入语句,这个类属于office365.sharepoint.client_context模块。
  2. 检查后续所有调用连接函数的位置,把错误的get_sharepoint_context_using_app()改成你实际定义的get_sharepoint_context_using_user(),如果你确实需要应用认证模式的连接逻辑,再单独实现对应名称的函数即可。

修复后的完整可运行代码如下:

# 补全缺失的ClientContext导入
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential

def get_sharepoint_context_using_user():
    sharepoint_url = 'https://abc.sharepoint.com'
    user_credentials = UserCredential("johndoe@gmail.com", "fakePass123")
    ctx = ClientContext(sharepoint_url).with_credentials(user_credentials)
    return ctx

# 调用示例:注意函数名要和定义完全一致
if __name__ == "__main__":
    ctx = get_sharepoint_context_using_user()
    # 在此处编写后续SharePoint操作逻辑
    # 例:web = ctx.web.get().execute_query()
额外提示

不建议在代码中硬编码明文账号密码,正式使用时建议通过环境变量、配置文件等方式读取敏感凭据,避免凭据泄露。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 20:45:49