我正在尝试使用Python连接到SharePoint Online网站。我在GitHub上找到了Office365-REST-Python-Client,并一直在使用它作为指南。我使用过" pip install Office365-REST-Python-Client"它安装没有任何问题。在示例文件夹中,我跟随名为" listitems_operations_alt.py"的文件。如果我将代码粘贴到我的python文件中并且根本不改变它,我会收到一条错误消息," NameError:name' urlparse'未定义"。如果我尝试更改网址以匹配我的SharePoint Online网站的网址,则会收到错误" KeyError:' mysite.sharepoint.com'"。我不确定是什么导致了这个问题。下面是我的代码。
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) # Web resource endpoint
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) # Web resource endpoint
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['mysite.sharepoint.com'])
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())
答案 0 :(得分:2)
如果从python包索引安装Office365-REST-Python-Client
package,那么不幸的是它的版本(2.0.0
)已经过时,特别是它不支持Python 3运行时,这可能就是为什么发生提供的错误。
尝试从GitHub安装最新版本(2.1.1
),如下所示:
pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git
示例
import json
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.client_request import ClientRequest
from office365.runtime.utilities.request_options import RequestOptions
from office365.sharepoint.client_context import ClientContext
settings = {
'url': 'https://contoso.sharepoint.com/',
'user_credentials': {
'username': '',
'password': ''
}
}
def read_list_items(context, list_title):
"""Read list items example"""
request = ClientRequest(context)
options = RequestOptions("{0}web/lists/getbyTitle('{1}')/items".format(context.service_root_url, list_title))
options.set_header('Accept', 'application/json; odata=nometadata')
print("Retrieving list items from List {0}".format(list_title))
response = request.execute_request_direct(options)
data = json.loads(response.content)
for item in data['value']:
print("Item title: {0}".format(item["Title"]))
if __name__ == '__main__':
ctx_auth = AuthenticationContext(url=settings['url'])
if ctx_auth.acquire_token_for_user(username=settings['user_credentials']['username'],
password=settings['user_credentials']['password']):
target_list_title = "Tasks"
ctx = ClientContext(settings['url'], ctx_auth) # Initialize client context
read_list_items(ctx, target_list_title)
else:
print(ctx_auth.get_last_error())