首页 > 解决方案 > 如何使用 Python 访问共享点站点作为 API

问题描述

我正在尝试使用 python 以 api 的形式访问共享点站点来下载文件。

到目前为止,我已经在 python 中尝试了“shareplum”、“office365”和“sharepy”模块。

每次由于用户名或密码无效而导致身份验证错误。

但是我可以使用相同的用户名和密码从 Web 浏览器登录到该共享点站点。

我应该遵循什么方法或应该使用哪种身份验证?

问候桑塔努

共享李子:

from shareplum import Site, Office365
from shareplum.site import Version
import json
import os

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
config_path = '\\'.join([ROOT_DIR, 'config_1.json'])

with open(config_path) as config_file:
    config = json.load(config_file)
    config = config['share_point']

USERNAME = config['user']
PASSWORD = config['password']
SHAREPOINT_URL = config['url']
SHAREPOINT_SITE = config['site']
SHAREPOINT_DOC = config['doc_library']


def auth():
    authcookie = Office365(SHAREPOINT_URL, username=USERNAME, password=PASSWORD).GetCookies()
    print(f"authcookie: {authcookie}")
    site = Site(SHAREPOINT_SITE, version=Version.v365, authcookie=authcookie)
    print(f"site: {site}")
    return site


def connect_folder(folder_name):
    auth_site = auth()
    print(f"auth_site: {auth_site}")
    sharepoint_dir = '/'.join([SHAREPOINT_DOC, folder_name])
    print(f"sharepoint_dir: {sharepoint_dir}")
    folder = auth_site.Folder(sharepoint_dir)
    print(f"folder: {folder}")
    return folder


def download_file(file_name, folder_name):
    _folder = connect_folder(folder_name)
    print(f"_folder: {_folder}")
    return _folder.get_file(file_name)


def run():
    # set file name
    file_name = 'Hardy_ServiceReporting_Aug2021.csv'

    # set the folder name
    folder_name = 'Problem Management'

    # get file
    file = download_file(file_name, folder_name)
    print(file)


if __name__ == "__main__":
    run()

错误:Error from Office 365:', 'AADSTS50126: Error validating credentials due to invalid username or password.'

办公室365:

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
import json
import os


ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
config_path = '\\'.join([ROOT_DIR, 'config_1.json'])

with open(config_path) as config_file:
    config = json.load(config_file)
    config = config['share_point']

USERNAME = config['user']
PASSWORD = config['password']
SHAREPOINT_URL = config['url']
SHAREPOINT_SITE = config['site']
SHAREPOINT_DOC = config['doc_library']
FOLDER = "Problem Management"

url = SHAREPOINT_SITE + "/_api/web/GetFolderByServerRelativeUrl('{}/{}')/Files".format(SHAREPOINT_DOC, FOLDER)
print(f"url: {url}")
ctx_auth = AuthenticationContext(url)
print(f"ctx_auth: {ctx_auth}")
ctx_auth.acquire_token_for_user(USERNAME, PASSWORD)
ctx = ClientContext(url, ctx_auth)
print(f"ctx: {ctx}")

错误:An error occurred while retrieving token from XML response: AADSTS53003: Access has been blocked by Conditional Access policies. The access policy does not allow token issuance.

标签: pythonapisharepoint

解决方案


推荐阅读