通过应用程序登录方法(客户端 ID、秘密和租户 ID)连接到 SharePoint 以写入/读取文件,但无法获得身份验证。
我已经尝试过以下代码:
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.client_credential import ClientCredential
from office365.runtime.auth.authentication_context import AuthenticationContext
context = ClientContext(SITE_URL).with_credentials(
ClientCredential(CLIENT_ID, CLIENT_SECRET))
cert_credentials = {
"tenant": TENANT_ID,
"client_id": CLIENT_ID,
"thumbprint": test_cert_thumbprint,
"cert_path": "{0}/../selfsignkey.pem".format(os.path.dirname(__file__)),
}
ctx = ClientContext(test_site_url).with_client_certificate(**cert_credentials)
current_web = ctx.web.get().execute_query()
print("{0}".format(current_web.url))
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
class SharepointService:
app_principal = {'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET}
context_auth = AuthenticationContext(url=site_url)
token = context_auth.acquire_token_for_app(client_id=app_principal['client_id'], client_secret=app_principal['client_secret'])
print(token)
ctx = ClientContext(site_url, context_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web site title: {0}".format(web.properties['Title']))
您可以参考以下代码来写入或读取文件
from shareplum import Office365
from shareplum.site import Version
# Replace these values with your SharePoint information
site_url = "https://your-sharepoint-site-url"
client_id = "your-client-id"
client_secret = "your-client-secret"
tenant_id = "your-tenant-id"
# Specify the site version (2013, 2016, Online)
version = Version.v2016
# SharePoint library and file information
library_name = "Documents"
file_path = "/Shared Documents/YourFile.txt"
# Connect to SharePoint
authcookie = Office365(site_url, username=None, password=None).GetAppOnlyAccessToken(client_id, client_secret, tenant_id)
site = Office365(site_url, authcookie=authcookie).GetSite()
# Open the SharePoint library
sp_library = site.List(library_name)
sp_library.GetListItems()
# Read file content
file_content = sp_library.get_file(file_path).read()
print("File Content:")
print(file_content.decode("utf-8"))
# Write to file
new_file_content = "Hello, SharePoint! This is a new content."
sp_library.upload_file(file_path, new_file_content.encode("utf-8"))
print("File has been updated successfully.")