All of the setup on the Sharepoint side gave me the connection details. Here is my Python that I can’t get to work. Dummy values used in the example.
import json
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.authentication_context import AuthenticationContext
# Function to get secrets (replace with your method of fetching secrets)
def get_secret(secret_name):
# Mock function to simulate retrieving secrets
return json.dumps({
"SHAREPOINT_SITE_URL": "aaaaa",
"SHAREPOINT_CLIENT_ID": "bbbb",
"SHAREPOINT_CLIENT_SECRET": "ccccc",
"TENANT_ID": "dddd"
})
def connect_to_sharepoint():
try:
# Fetch connection data
sp_conn_data = json.loads(get_secret("test"))
# Extract connection details
sp_site = sp_conn_data["SHAREPOINT_SITE_URL"]
sp_client = sp_conn_data["SHAREPOINT_CLIENT_ID"]
sp_secret = sp_conn_data["SHAREPOINT_CLIENT_SECRET"]
tenant_id = sp_conn_data["TENANT_ID"]
# Authenticate to SharePoint
authority_url = f"https://login.microsoftonline.com/{tenant_id}"
auth_context = AuthenticationContext(authority_url)
client_credential = ClientCredential(sp_client, sp_secret)
token_response = auth_context.acquire_token_for_app(sp_site, client_credential)
if not token_response:
raise Exception(auth_context.get_last_error())
access_token = token_response['accessToken']
ctx = ClientContext(sp_site).with_access_token(access_token)
# Test the connection
web = ctx.web
ctx.load(web)
ctx.execute_query()
print(f"Connected to SharePoint site: {web.properties['Title']}")
except Exception as e:
print(f"Error connecting to SharePoint: {str(e)}")
if __name__ == "__main__":
connect_to_sharepoint()
I keep getting this error but have tried multiple connection approaches.
Error connecting to SharePoint: 'AuthenticationContext' object is not subscriptable