使用Python连接SharePoint Online时遇NameError与KeyError问题求助
Hey there! Let's break down and fix those two errors you're running into with the Office365-REST-Python-Client:
1. Fixing the NameError: name 'urlparse' is not defined
The example code you're using was likely written for Python 2, but in Python 3 the urlparse module was moved to urllib.parse. The library relies on this module under the hood, so you just need to add the import at the top of your script:
from urllib.parse import urlparse
This will resolve the missing reference error immediately.
2. Fixing the KeyError: 'mysite.sharepoint.com'
This error pops up because your settings dictionary doesn't have a key named 'mysite.sharepoint.com'. Let's look at where you went wrong:
- The
AuthenticationContextexpects your full SharePoint site URL as its parameter, not a random key from your settings. - You're already using
settings['url']elsewhere in your code, so yoursettings.pyfile probably uses that key for the site URL.
Here's how to fix it:
First, double-check your examples/settings.py file to ensure it has entries like this (replace with your actual credentials):
settings = { 'url': 'https://mysite.sharepoint.com/sites/YourSpecificSite', 'username': 'your-work-email@domain.com', 'password': 'your-password' }
Then update the AuthenticationContext initialization line to use the correct settings key:
context_auth = AuthenticationContext(url=settings['url'])
Corrected Full Code
from urllib.parse import urlparse # Added for Python 3 compatibility from examples.settings import settings from office365.runtime.auth.authentication_context import AuthenticationContext from office365.runtime.client_request import ClientRequest def read_list_items(web_url, ctx_auth, list_title): """Read list items example""" request = ClientRequest(web_url, ctx_auth) request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items".format(web_url, list_title) print("Retrieving list items from List {0}".format(list_title)) data = request.execute_request_direct(request_url=request_url) for item in data['d']['results']: print("Item title: {0}".format(item["Title"])) def create_list_item(web_url, ctx_auth, list_title): """Create list item example""" request = ClientRequest(web_url, ctx_auth) request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items".format(web_url, list_title) print("Creating list item...") item_payload = {'__metadata': {'type': 'SP.Data.TasksListItem'}, 'Title': 'New Task'} data = request.execute_request_direct(request_url=request_url, data=item_payload) print("Task {0} has been successfully [created]".format(data['d']['Title'])) return data['d'] def update_list_item(web_url, ctx_auth, list_title, item_id): """Update list item example""" request = ClientRequest(web_url, ctx_auth) request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items({2})" \ .format(web_url, list_title, item_id) print("Updating list item...") item_payload = {'__metadata': {'type': 'SP.Data.TasksListItem'}, 'Title': 'New Task (updated)'} headers = { 'IF-MATCH': '*', 'X-HTTP-Method': 'MERGE' } request.execute_request_direct(request_url=request_url, headers=headers, data=item_payload) print("Task has been successfully [updated]") def delete_list_item(web_url, ctx_auth, list_title, item_id): """Delete list item example""" request = ClientRequest(web_url, ctx_auth) request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items({2})" \ .format(web_url, list_title, item_id) print("Deleting list item...") headers = { 'IF-MATCH': '*', 'X-HTTP-Method': 'DELETE' } request.execute_request_direct(request_url=request_url, headers=headers) print("Task has been successfully [deleted]") if __name__ == '__main__': context_auth = AuthenticationContext(url=settings['url']) if context_auth.acquire_token_for_user(username=settings['username'], password=settings['password']): read_list_items(settings['url'], context_auth, "Tasks") task_item = create_list_item(settings['url'], context_auth, "Tasks") update_list_item(settings['url'], context_auth, "Tasks", task_item['Id']) delete_list_item(settings['url'], context_auth, "Tasks", task_item['Id']) else: print(context_auth.get_last_error())
Quick Extra Notes
- Ensure your SharePoint list is actually named "Tasks"—if it's a different name, replace that string in the code with your list's exact title.
- The
SP.Data.TasksListItemvalue in the payload is specific to a list named "Tasks". For other lists, you can find the correct entity type by visitinghttps://your-site-url/_api/web/lists/getbyTitle('YourListName')?$select=ListItemEntityTypeFullNamein your browser. - If you use multi-factor authentication (MFA), the
acquire_token_for_usermethod won't work—you'll need to switch to client credentials or certificate-based authentication instead.
内容的提问来源于stack exchange,提问作者Zach

