Microsoft 365和Microsoft图库,用于Python
使用PIP:
pip install Office365-REST-Python-Client
另外,最新版本可以通过GitHub直接安装:
pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git
对于以下示例,可以在Azure门户网站中找到相关的凭证。
访问步骤:
ClientContext
Client提供了对旧版SharePoint REST和ONEDRIVE的支持,用于业务REST API,这是支持版本的列表:
支持以下验证流量:
此auth方法与SharePoint本地的SharePoint本地兼容兼容,并且仍然相关模型,作为在线SharePoint在线,可用以下方法:
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
用法:
user_credentials = UserCredential('{username}','{password}')
ctx = ClientContext('{url}').with_credentials(user_credentials)
示例:connect_with_user_credential.py
文档:
示例:connect_with_client_certificate.py
通过本地浏览器交互式登录IE
先决条件:
在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查询的方法:
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' ]))
或通过方法链(又称流利界面):
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' ]))
SharePointRequest class
- 您在构建休息查询的位置(不涉及模型)
该示例演示了如何读取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环境的支持。目前支持:
为了启用身份验证到GCC高端点,请添加environment='GCCH'
参数时,使用.with_user_credentials
, .with_client_credentials
或.with_credentials
调用ClientContext class
例子:
from office365 . sharepoint . client_context import ClientContext
client_credentials = ClientCredential ( '{client_id}' , '{client_secret}' )
ctx = ClientContext ( '{url}' ). with_credentials ( client_credentials , environment = 'GCCH' )
支持的API列表:
由于Microsoft Graph和Outlook API端点都可以使用Outlook REST API,因此可用以下客户端:
v2.0
版本的GraphClient
(如今,请参考基于Microsoft Graph Graph的Outlook Rest API的过渡)OutlookClient
针对Outlook API v1.0
版本(不建议使用v1.0
版本。)python的Microsoft身份验证库(MSAL)用作依赖关系,用作默认库来获取令牌以调用Microsoft Graph API。
使用Microsoft身份验证库(MSAL)进行Python
注意:在提供的示例中,正在通过客户凭证流通过客户凭证流获得访问令牌。可以在此处找到其他形式的令牌获取: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 Endpoint发送电子邮件。
注意:访问令牌正在通过客户端凭证流获得
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 = [ "[email protected]" ]
). execute_query ()
其他示例和方案:
有关其他场景,请参阅示例部分
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,该URL对应于list available drives
端点
注意:访问令牌正在通过客户端凭证流获得
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 ))
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示例部分。
用于获得令牌的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 ()
其他示例:
有关其他场景,请参阅示例部分
该图书馆在个人或组织帐户中对用户的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 ()
该示例演示了如何创建一个新的计划者任务,该任务对应于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 ()
安装客户端库时将安装以下库:
Jetbrains
的强大Python Ide Pycharm
。