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
。