Office365-REST-Python-Client
Office365-REST-Python-Client copied to clipboard
directory creation and file upload to team and channel
I followed the instructions here to set up a client id and secret. https://github.com/vgrem/Office365-REST-Python-Client/wiki/How-to-connect-to-SharePoint-Online-and-and-SharePoint-2013-2016-2019-on-premises--with-app-principal
from office365.runtime.auth.client_credential import ClientCredential
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
client_id = ""
secret = ""
sharepoint_url = "https://{organization}.sharepoint.com/sites/Some Team"
def get_sharepoint_context_using_app():
client_credentials = ClientCredential(client_id, secret)
ctx = ClientContext(sharepoint_url).with_credentials(client_credentials)
return ctx
def get_sharepoint_context_using_user():
user_credentials = UserCredential(r"SvcAcctShareGate", r"%a$FotT583aJEwpx&8Cq")
ctx = ClientContext(sharepoint_url).with_credentials(user_credentials)
return ctx
def create_sharepoint_directory(dir_name: str):
if dir_name:
ctx = get_sharepoint_context_using_app()
result = ctx.web.folders.add(f'Shared Documents/{dir_name}').execute_query()
if result:
# documents is titled as Shared Documents for relative URL in SP
relative_url = f'Shared Documents/{dir_name}'
return relative_url
def upload_to_sharepoint(dir_name: str, file_name: str):
sp_relative_url = create_sharepoint_directory(dir_name)
ctx = get_sharepoint_context_using_user()
target_folder = ctx.web.get_folder_by_server_relative_url(sp_relative_url)
with open(file_name, 'rb') as content_file:
file_content = content_file.read()
target_folder.upload_file(file_name, file_content).execute_query()
create_sharepoint_directory('test directory')
when the sharepoint_url is only https://{organization}.sharepoint.com I get :
office365.runtime.client_request_exception.ClientRequestException: ('-2130247139, Microsoft.SharePoint.SPException', '(null) "Shared Documents/test directory" not found.', "500 Server Error: Internal Server Error for url: https://{organization}.sharepoint.com/_api/Web/folders/Add('Shared%20Documents%2Ftest%20directory')")
when sites/Some Team is appended I get:
ValueError: {"error":"invalid_request","error_description":"AADSTS900023: Specified tenant identifier 'none' is neither a valid DNS name, nor a valid external domain. Trace ID: b3145e0d-dcbd-4504-8cd5-927e6e59d106 Correlation ID: b3f74c3f-83aa-4815-b7a1-d3b21686996a Timestamp: 2024-05-01 18:14:32Z","error_codes":[900023],"timestamp":"2024-05-01 18:14:32Z","trace_id":"b3145e0d-dcbd-4504-8cd5-927e6e59d106","correlation_id":"b3f74c3f-83aa-4815-b7a1-d3b21686996a","error_uri":"https://accounts.accesscontrol.windows.net/error?code=900023"}
What am I missing?