Python用のMicrosoft 365およびMicrosoftグラフライブラリ
PIPを使用してください:
pip install Office365-REST-Python-Client
または、最新バージョンをGitHub経由で直接インストールすることもできます。
pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git
次の例では、関連する資格情報はAzureポータルにあります。
アクセスの手順:
ClientContextクライアントは、サポートされているバージョンのリストであるBusiness Rest APIのレガシーSharePoint RestとOneDriveのサポートを提供します。
次の認証フローがサポートされています。
このAUTHメソッドは、SharePointオンプレミスの両方のSharePoint Onlineとしての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
インタラクティブにログインするには、ローカルブラウザを介して
前提条件:
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クエリを実行するには、 2つのアプローチがあります。
ClientContext class - Web 、 ListItemなどのSharePointリソースをターゲットにする場所(推奨) 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' ])) 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ハイエンドポイントに認証を有効にするには、 .with_user_credentials 、 .with_client_credentials 、または.with_credentialsを使用してClientContext classを呼び出すときに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' )サポートされているAPIのリスト:
Outlook REST APIはMicrosoftグラフとOutlook APIエンドポイントの両方で利用可能であるため、次のクライアントが利用可能です。
v2.0バージョンをターゲットにするGraphClient (最近では、詳細についてはMicrosoft GraphベースのOutlook REST APIへの移行を参照してください)v1.0バージョンをターゲットにするOutlookClient ( v1.0バージョンが非推奨されているため、使用は推奨されません。)依存関係として提供されるPython用のMicrosoft Authentication Library(MSAL)は、デフォルトのライブラリとして使用され、Microsoft Graph APIを呼び出すトークンを取得します。
PythonにMicrosoft Authentication Library(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認証に関しては、Adalなどの別のOAuth Spec準拠ライブラリもサポートされています。
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グラフAPIリファレンス
依存関係として提供されるPython用のMicrosoft Authentication Library(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 )) 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 Authentication Library(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 。