跳转到主要内容

Microsoft 365 & Microsoft Graph Python库

项目描述

关于

Microsoft 365 & Microsoft Graph Python库

使用方法

  1. 安装
  2. 使用SharePoint API
  3. 使用Outlook API
  4. 使用OneDrive和SharePoint API v2 API
  5. 使用Teams API
  6. 使用OneNote API
  7. 使用Planner API

状态

Downloads PyPI PyPI pyversions Build Status

安装

使用pip

pip install Office365-REST-Python-Client

注意

或者可以直接通过GitHub安装最新版本

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

身份验证

以下示例中的相关凭据可以在 Azure Portal 中找到。

访问步骤

  1. 登录 Azure Portal 的主页
  2. 使用门户右上角的三个横条导航到 "Azure Active Directory"
  3. 在左侧导航面板中选择 "应用程序注册"
  4. 搜索并选择您的相关应用程序
  5. 在应用程序的 "概览" 页面上,客户端 ID 可在 "应用程序 (客户端) ID" 下找到
  6. 在应用程序的 "证书和密钥" 页面上,客户端密钥可在 "客户端密钥" 的 "值" 下找到。如果没有客户端密钥,请在此处创建一个。

使用SharePoint API

ClientContext 客户端提供了对旧版 SharePoint REST 和 OneDrive for Business REST API 的支持,支持的版本列表

身份验证

以下身份验证流程受到支持

1. 使用 SharePoint App-Only 实体(客户端凭据流程)

此身份验证方法与 SharePoint 本地以及 SharePoint 本地和 SharePoint Online 中的仍相关的模型兼容,以下方法可用

  • ClientContext.with_credentials(client_credentials)
  • ClientContext.with_client_credentials(client_id, client_secret)

使用方法

client_credentials = ClientCredential('{client_id}','{client_secret}')
ctx = ClientContext('{url}').with_credentials(client_credentials)

文档

示例: connect_with_app_principal.py

2. 使用用户名和密码

使用方法

user_credentials = UserCredential('{username}','{password}')
ctx = ClientContext('{url}').with_credentials(user_credentials)

示例: connect_with_user_credential.py

3. 使用 Azure AD 应用程序(证书凭据流程)

文档

示例: connect_with_client_certificate.py

4. 交互式

以交互方式登录,即通过本地浏览器

先决条件

在 Azure Portal 中,将您的 "移动和桌面应用程序" 的重定向 URI 配置为 http://localhost

示例: connect_interactive.py

使用方法

from office365.sharepoint.client_context import ClientContext
ctx = ClientContext("{site-url}").with_interactive("{tenant-name-or-id}", "{client-id}")
me = ctx.web.current_user.get().execute_query()
print(me.login_name)

示例

执行 API 查询有两种可用方法

  1. ClientContext 类 - 其中您针对 SharePoint 资源,如 WebListItem 等(推荐)
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
site_url = "https://{your-tenant-prefix}.sharepoint.com"
ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web title: {0}".format(web.properties['Title']))

或者通过方法链(又称流畅界面)

from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
site_url = "https://{your-tenant-prefix}.sharepoint.com"
ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
web = ctx.web.get().execute_query()
print("Web title: {0}".format(web.properties['Title']))
  1. SharePointRequest 类 - 其中您构建 REST 查询(不涉及模型)

    此示例演示了如何读取 Web 属性

import json
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.request import SharePointRequest
site_url = "https://{your-tenant-prefix}.sharepoint.com"
request = SharePointRequest(site_url).with_credentials(UserCredential("{username}", "{password}"))
response = request.execute_request("web")
json = json.loads(response.content)
web_title = json['d']['Title']
print("Web title: {0}".format(web_title))

示例列表

有关其他场景,请参阅 示例部分

非标准 SharePoint Online 环境的支持

非标准 SharePoint Online 环境的支持目前正在实施。目前支持

  • GCC 高

要启用对 GCC 高端点的身份验证,在调用 ClientContext 类.with_user_credentials.with_client_credentials.with_credentials 时,添加 environment='GCCH' 参数

示例

from office365.sharepoint.client_context import ClientContext
client_credentials = ClientCredential('{client_id}','{client_secret}')
ctx = ClientContext('{url}').with_credentials(client_credentials, environment='GCCH')

使用Outlook API

支持的 API 列表

由于 Outlook REST API 可在 Microsoft Graph 和 Outlook API 端点中找到,因此以下客户端可用

  • GraphClient 针对 Outlook API v2.0 版本(现在更推荐,有关从 Outlook REST API 过渡到基于 Microsoft Graph 的 Outlook REST API 的详细信息,请参阅 transition to Microsoft Graph-based Outlook REST API
    - OutlookClient 针对 Outlook API v1.0 版本(不建议使用,因为 v1.0 版本正在被弃用。)

身份验证

Python 的 Microsoft 身份验证库(MSAL) 作为依赖项提供,是获取调用 Microsoft Graph API 的令牌的默认库。

使用 Python 的 Microsoft 身份验证库(MSAL)

注意:提供的示例中通过 客户端凭据流 获取访问令牌。其他令牌获取方式可在此找到:https://msal-python.readthedocs.io/en/latest/

import msal
from office365.graph_client import GraphClient

def acquire_token():
    """
    Acquire token via MSAL
    """
    authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
    app = msal.ConfidentialClientApplication(
        authority=authority_url,
        client_id='{client_id}',
        client_credential='{client_secret}'
    )
    token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    return token


client = GraphClient(acquire_token)

但在 Microsoft Graph API 身份验证方面,还支持其他符合 OAuth 规范的库,例如 adal

使用 ADAL Python

使用方法

import adal
from office365.graph_client import GraphClient

def acquire_token_func():
    authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
    auth_ctx = adal.AuthenticationContext(authority_url)
    token = auth_ctx.acquire_token_with_client_credentials(
        "https://graph.microsoft.com",
        "{client_id}",
        "{client_secret}")
    return token

client = GraphClient(acquire_token_func)

示例

示例演示了如何通过 Microsoft Graph 端点 发送电子邮件。

注意:通过 客户端凭据流 获取访问令牌

from office365.graph_client import GraphClient

client = GraphClient(acquire_token_func)

client.me.send_mail(
    subject="Meet for lunch?",
    body="The new cafeteria is open.",
    to_recipients=["fannyd@contoso.onmicrosoft.com"]
).execute_query()

其他示例和场景

有关其他场景,请参阅 示例部分

与 OneDrive 和 SharePoint v2 API 一起工作

文档

OneDrive Graph API 参考

身份验证

Python 的 Microsoft 身份验证库(MSAL) 作为依赖项用于获取令牌

import msal

def acquire_token_func():
    """
    Acquire token via MSAL
    """
    authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
    app = msal.ConfidentialClientApplication(
        authority=authority_url,
        client_id='{client_id}',
        client_credential='{client_secret}'
    )
    token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    return token

示例

示例:列出可用的驱动器

示例演示了如何枚举并打印与 列出可用驱动器 端点 对应的驱动器 URL

注意:通过 客户端凭据流 获取访问令牌

from office365.graph_client import GraphClient

tenant_name = "contoso.onmicrosoft.com"
client = GraphClient(acquire_token_func)
drives = client.drives.get().execute_query()
for drive in drives:
    print("Drive url: {0}".format(drive.web_url))
示例:下载 DriveItem(文件夹属性)的内容
from office365.graph_client import GraphClient
client = GraphClient(acquire_token_func)
# retrieve drive properties 
drive = client.users["{user_id_or_principal_name}"].drive.get().execute_query()
# download files from OneDrive into local folder 
with tempfile.TemporaryDirectory() as path:
    download_files(drive.root, path)

其中

def download_files(remote_folder, local_path):
    drive_items = remote_folder.children.get().execute_query()
    for drive_item in drive_items:
        if drive_item.file is not None:  # is file?
            # download file content
            with open(os.path.join(local_path, drive_item.name), 'wb') as local_file:
                drive_item.download(local_file).execute_query()

其他示例

有关更多示例,请参阅 OneDrive 示例部分

与 Microsoft Teams API 一起工作

身份验证

Python 的 Microsoft 身份验证库(MSAL) 作为依赖项用于获取令牌

示例

示例:在组下创建新的团队

示例演示了如何创建一个新的团队,该团队对应于 创建团队 端点

from office365.graph_client import GraphClient
client = GraphClient(acquire_token_func)
new_team = client.groups["{group-id}"].add_team().execute_query_retry()

其他示例

有关其他场景,请参阅 示例部分

与 Microsoft Onenote API 一起工作

该库支持在个人或组织帐户中调用用户的 OneNote 笔记本、部分和页面

示例:创建新页面

from office365.graph_client import GraphClient
client = GraphClient(acquire_token_func)

files = {}
with open("./MyPage.html", 'rb') as f, \
    open("./MyImage.png", 'rb') as img_f, \
    open("./MyDoc.pdf", 'rb') as pdf_f:
    files["imageBlock1"] = img_f
    files["fileBlock1"] = pdf_f
    page = client.me.onenote.pages.add(presentation_file=f, attachment_files=files).execute_query()

与 Microsoft Planner API 一起工作

示例演示了如何创建新的 plannerTask,该任务对应于 创建 plannerTask 端点

from office365.graph_client import GraphClient

client = GraphClient(acquire_token_func)
task = client.planner.tasks.add(title="New task", planId="--plan id goes here--").execute_query()

第三方库和依赖项

在安装客户端库时将安装以下库

感谢

强大的 Python IDE Pycharm 来自 Jetbrains

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分发

office365_rest_python_client-2.5.13.tar.gz (600.0 kB 查看哈希值)

上传时间:

构建分发

Office365_REST_Python_Client-2.5.13-py3-none-any.whl (1.2 MB 查看哈希值)

上传时间: Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面