Получите keyerror при попытке авторизации себя на сайте sharepoint - PullRequest
0 голосов
/ 18 мая 2018

Я пытаюсь подключиться к сайту SharePoint Online с помощью Python.Я нашел Office365-REST-Python-Client на GitHub и использовал его в качестве руководства.Я использовал «pip install Office365-REST-Python-Client», и он установился без проблем.В папке примеров я следую вместе с файлом с именем «listitems_operations_alt.py».Если я вставляю код в файл python и не изменяю его вообще, я получаю сообщение об ошибке: «NameError: name 'urlparse' не определено».Если я пытаюсь изменить URL-адрес, чтобы он соответствовал URL-адресу моего сайта 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())

1 Ответ

0 голосов
/ 20 мая 2018

Если вы устанавливаете Office365-REST-Python-Client пакет из индекса пакета python, то, к сожалению, его версия (2.0.0) уже устарела, в частности, он не поддерживает среду выполнения Python 3, что, вероятно, является причиной, почемупри условии возникновения ошибки.

Попробуйте установить последнюю версию (2.1.1) вместо GitHub, например:

pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git 

enter image description here

Пример

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())
...