Skip to main content

适用于 Python 的 Microsoft 365 和 Microsoft 图形库

项目描述

关于

适用于 Python 的 Office 365 和 Microsoft Graph 库

用法

  1. 安装
  2. 使用 SharePoint API
  3. 使用 Outlook API
  4. 使用 OneDrive API
  5. 使用团队 API
  6. 使用 OneNote API
  7. 使用规划器 API

地位

下载 派皮 PyPI 版本 构建状态

安装

使用点子:

pip install Office365-REST-Python-Client

笔记

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

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

使用 SharePoint API

支持的 API 版本列表:

验证

支持以下身份验证流程:

例子

两种方法可用于执行 API 查询:

  1. ClientContext class- 定位 SharePoint 资源的位置,例如Web,ListItem等(推荐)
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']))

或者通过方法链接(又名 Fluent 接口):

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. RequestOptions class- 在哪里构建 REST 查询(不涉及模型)

    该示例演示了如何读取Web属性:

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

示例列表:

有关其他方案,请参阅示例部分

使用 Outlook API

支持的 API 列表:

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

验证

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

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

注意:访问令牌是通过提供的示例中的客户端凭据流获取的

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 API

文档

OneDrive 图形 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

例子

示例:列出可用驱动器

该示例演示了如何枚举和打印与list available drives端点对应的驱动器的 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 团队 API

验证

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

例子

示例:在一个组下创建一个新团队

该示例演示如何在与端点对应的组下创建新团队Create team

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 笔记本、分区和页面方面支持 OneNote API

示例:创建一个新页面

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

该示例演示了如何创建一个与Create 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()

第三方库和依赖项

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