【问题标题】:How to upload a file to sharepoint site using python script如何使用 python 脚本将文件上传到共享点站点
【发布时间】:2022-01-18 10:06:22
【问题描述】:

有没有办法使用 python 脚本在 sharepoint 站点上上传文件?我尝试安装 haufe.sharepoint,但它似乎在安装时无法获取 ntlm,而且我什至无法在没有安装 ntlm 的情况下使用连接器模块。

我还尝试使用 openpyxl 将 excel 文件保存到服务器位置(因此将其保存到 \server\sharepointsite\files 之类的目录,而不是通过 URL 连接),但看起来文件在之后仍然签出文件已保存..

我将不胜感激。谢谢!!

【问题讨论】:

标签: python python-2.7 sharepoint openpyxl


【解决方案1】:

我首先要说这个示例改编自 Office365-REST-Python-Client 的示例。它使用 rest api 与在线共享点一起工作。

https://github.com/vgrem/Office365-REST-Python-Client/blob/master/examples/sharepoint/files/upload_file.py

您可能希望上传到 [baseurl][site][folder][file] 的示例 url。 https://your_company.sharepoint.com/path/to/site/Shared Documents/file.txt

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

baseurl = 'https://your_company.sharepoint.com'
basesite = '/path/to/site' # every share point has a home.
siteurl = baseurl + basesite 

localpath = ./file.txt
remotepath = Shared Documents/file.txt # existing folder path under sharepoint site.

ctx_auth = AuthenticationContext(url)
ctx_auth.acquire_token_for_user(username, password)
ctx = ClientContext(siteurl, ctx_auth) # make sure you auth to the siteurl.

with open(localpath, 'rb') as content_file:
    file_content = content_file.read()

dir, name = os.path.split(remotepath)
file = ctx.web.get_folder_by_server_relative_url(dir).upload_file(name, file_content).execute_query()

【讨论】:

【解决方案2】:

haufe.sharepoint 仅适用于共享点列表,但您可能需要访问文档库。

您应该在 Sharepoint 的 REST API 的帮助下使用 Python Requests

如果您的共享点站点不支持 BasicAuth,我推荐使用 requests_ntlm 包。

由于其他原因,它对我不起作用,但也许它对您有所帮助。

【讨论】:

  • 请问为什么它不适合您?顺便说一下 +1。
【解决方案3】:

您可以使用 SharePlum 上传文件

安装 SharePlum:pip install SharePlum 并尝试以下代码

import requests
from shareplum import Office365

# Set Login Info
username = '<username>'
password = '<password>'
site_name = '<site_name>'
base_path = 'https://<domain_name>.sharepoint.com'
doc_library = 'Shared%20Documents'
nested_folder = 'Shared%20Documents/<folder1>/<folder2>' #if you want to upload in nested folders else nested_folder = doc_library
file_name = "my_file.zip" #when your file in the same directory

# Obtain auth cookie
authcookie = Office365(base_path, username=username, password=password).GetCookies()
session = requests.Session()
session.cookies = authcookie
session.headers.update({'user-agent': 'python_bite/v1'})
session.headers.update({'accept': 'application/json;odata=verbose'})

session.headers.update({'X-RequestDigest': 'FormDigestValue'})
response = session.post(url=base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='a.txt',overwrite=true)",
                         data="")
session.headers.update({'X-RequestDigest': response.headers['X-RequestDigest']})

# Upload file
with open(file_name, 'rb') as file_input:
    try:
        response = session.post(
            url=base_path + "/sites/" + site_name + f"/_api/web/GetFolderByServerRelativeUrl('" + nested_folder + "')/Files/add(url='"
            + file_name + "',overwrite=true)",

            data=file_input)
        print("response: ", response.status_code) #it returns 200
        if response.status_code == '200':
            print("File uploaded successfully")
    except Exception as err:
        print("Something went wrong: " + str(err))

print('File Uploaded Successfully')

【讨论】:

  • 为我工作。感谢您对 Nurealam 的回答。但是1.如何指定未创建的nested_folder,如果嵌套文件夹不存在,则希望它通过创建嵌套文件夹来保存。 2. 这种方法在互联网上发送请求是否安全?
  • 1.您可能想在定义嵌套文件夹之前单独创建一个文件夹(查看如何创建文件夹:pypi.org/project/SharePlum),上面的代码不会自动创建文件夹,您会收到错误消息。 2. 是的,它是安全的,否则我不会使用。如果您不习惯使用它,您也可以使用 client_secret 和 client_id @shreeshkatti。
  • 注意:您可能无法访问abc.sharepoint.com,您可以通过abc-my.sharepoint.com 访问您自己的环境。
【解决方案4】:

我想我回答这个问题可能有点晚了。

以下解决方案对我有用-

在 Sharepoint 网页中,转到库工具>> 库>> 使用资源管理器命令打开(它位于连接到 Office 命令旁边右下角的小图标。

地址栏为我们提供了上传文件所需的地址。 记得从地址中删除“http:”或“https:”此地址是您上传文件的目的地。

接下来就可以使用shutil包上传文件了。

import shutil as sl
sl.copy(source,destination)

这应该可以帮助您将文件上传到 Sharepoint

免责声明 - 这在 Python 3.6 中运行良好

【讨论】:

    【解决方案5】:

    上面的答案对我不起作用。 我找到了一种简单而好方法,只需将驱动器映射到我的 sharepoint 文件夹,然后使用副本到该驱动器。

    import subprocess
    import shutil
    subprocess.call(r'net use Y: http://sharepoint/link/to/your/folder', shell=True)
    shutil.copy("link_to_local_file","Y:\\")
    

    除了复制之外,您还可以删除文件或像普通文件夹一样执行任何操作。

    【讨论】:

    • 这对我不起作用。什么是“净使用 Y:”?!?
    • @Mikus 我收到了这个错误,当我尝试你的建议时.. FileNotFoundError: [Errno 2] No such file or directory: 'Y:\\'
    【解决方案6】:

    我通过 rest api 调用在 python 中的 SharePoint 站点中创建了一个文件。请在下面找到我的代码。

    def CreateHomePage():
        server_relative_url = base_url+ '/_api/web/webinfos'
    
    r1 = requests.get(server_relative_url, auth=HttpNtlmAuth(username, password), headers = headers, verify=True)
    
    value = json.loads(r1.text)
    for row in value['d']['results']:
        if(row['Title'] == myvars['Site Name'].strip(' \t\n\r')):
            Id= row['ServerRelativeUrl']
    
    #Add Template and create file simultaneously
    title = myvars['Site Name'].strip(' \t\n\r')  
    post_url = root_url  +'GetFolderByServerRelativeUrl(\'/'+Id+'/Pages\')/Files/add(url=\'Home.aspx\',overwrite=true)'
    r2 = requests.post(post_url, auth=HttpNtlmAuth(username, password), headers = headers, verify=True)
    
    logger.debug("Creation of home page %d", r2.status_code)
    

    【讨论】:

      【解决方案7】:

      我创建了一个将附件上传到 SharePoint 列表的脚本 让我知道它是否有效

      import requests
      from shareplum import Office365
      
      # Obtain auth cookie
      authcookie = Office365('https://YOUR-NAME.sharepoint.com', username='YOUR-USERNAME',password='YOUR-PASSWORD').GetCookies()
      session = requests.Session()
      session.cookies = authcookie
      session.headers.update({'user-agent': 'python_bite/v1'})
      session.headers.update({'accept': 'application/json;odata=verbose'})
      
      # dirty workaround.... I'm getting the X-RequestDigest from the first failed call
      session.headers.update({'X-RequestDigest': 'FormDigestValue'})
      response = session.post(url="https://YOUR-NAME.sharepoint.com/sites/YOU-SITE/_api/web/GetFolderByServerRelativeUrl('YOUR-FOLDER')/Files/add(url='a.txt',overwrite=true)",data="")
      session.headers.update({'X-RequestDigest': response.headers['X-RequestDigest']})
      
      # perform the upload
      fileName = 'picture.png'
      file_name = 'images.png'
      with open(file_name, 'rb') as file_input:
          response = session.post(
              url="https://YOUR-NAME.sharepoint.com/sites/YOUR-SITE/_api/web/lists/getbytitle('ID-ROW-INTO-SHAREPOINT')/items(4)/AttachmentFiles/add(FileName='" + fileName + "')",data=file_input)
          print(response.text)
      

      【讨论】:

      • 嗨@Michelone,您能否在您的代码中添加一个示例。它是什么'NAME-LIST'?谢谢!
      • 嗨@VincentBénet 抱歉,我的错误不是('NAME-LIST')是共享点的行 ID
      猜你喜欢
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2020-10-16
      • 1970-01-01
      相关资源
      最近更新 更多