Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13981

Issue- Getting excel file from sharepoint using python

$
0
0

Error is coming while i am trying to get files from sharepoint using following python code. Here is the error msg : 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. Could anyone help me how to do that? Here is my code:

import osimport shutilfrom office365.runtime.auth.authentication_context import AuthenticationContextfrom office365.sharepoint.client_context import ClientContextsharepoint_url = "Sharepoint_site_url"site_url = "site url"username = "My_username"password = "Password"# File path componentslibrary_name = "Shared Documents"folder_name = "ABCD"# Construct the full file pathfile_path = f"https://xyz.sharepoint.com/sites/site_name/{library_name}/{folder_name}/"# Encode the file pathencoded_file_path = file_path.replace(" ", "%20")  # Replace spaces with %20print(encoded_file_path)# Authenticate with SharePointctx_auth = AuthenticationContext(sharepoint_url)if ctx_auth.acquire_token_for_user(username, password):    # Connect to SharePoint site    ctx = ClientContext(site_url, ctx_auth)    web = ctx.web    ctx.load(web)    # Get all files in the SharePoint folder    files = ctx.web.get_folder_by_server_relative_path(file_path).files    ctx.load(files)    ctx.execute_query()    # Create a folder on the C drive    c_drive_folder1 = "C:/ENTERP/Raw"    c_drive_folder2 = "C:/ENTERPR/Processed"    os.makedirs(c_drive_folder1, exist_ok=True)    os.makedirs(c_drive_folder2, exist_ok=True)    # Download and save each file to the C drive folderfor file in files:        print(1)        file_name = file.properties["Name"]        file_url = f"{site_url}/{library_name}/{folder_name}/{file_name}"        file_content = ctx.web.get_file_by_server_relative_path(file_url).read().execute_query()        # Save the file to the C drive folder        file_path_on_c_drive = os.path.join(c_drive_folder1, file_name)        with open(file_path_on_c_drive, "wb") as local_file:            local_file.write(file_content)        print(f"Downloaded and saved: {file_name} to {file_path_on_c_drive}")        print("Download process completed.")else:        print("Failed to authenticate with SharePoint.")

Any alternate solution suggestion would be appreciated as well.


Viewing all articles
Browse latest Browse all 13981

Trending Articles