Perpustakaan Grafik Microsoft 365 & Microsoft untuk Python
Gunakan Pip:
pip install Office365-REST-Python-Client
Atau versi terbaru dapat diinstal langsung melalui GitHub:
pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git
Untuk contoh -contoh berikut, kredensial yang relevan dapat ditemukan di portal Azure.
Langkah untuk diakses:
Klien ClientContext memberikan dukungan untuk istirahat SharePoint dan OneDrive untuk API Business REST, daftar versi yang didukung:
Aliran auth berikut didukung:
Metode auth ini kompatibel dengan SharePoint di tempat dan model yang masih relevan di kedua SharePoint di tempat sebagai SharePoint Online, metode berikut tersedia:
ClientContext.with_credentials(client_credentials)ClientContext.with_client_credentials(client_id, client_secret)Penggunaan:
client_credentials = ClientCredential('{client_id}','{client_secret}')
ctx = ClientContext('{url}').with_credentials(client_credentials)
Dokumentasi:
Contoh: connect_with_app_principal.py
Penggunaan:
user_credentials = UserCredential('{username}','{password}')
ctx = ClientContext('{url}').with_credentials(user_credentials)
Contoh: connect_with_user_credential.py
Dokumentasi:
Contoh: connect_with_client_certificate.py
untuk masuk secara interaktif yaitu melalui browser lokal
Prasyarat:
Di Azure Portal, konfigurasikan uri redirect dari "aplikasi seluler dan desktop" Anda sebagai
http://localhost.
Contoh: connect_interactive.py
Penggunaan:
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 )Ada dua pendekatan yang tersedia untuk melakukan pertanyaan API:
ClientContext class - Di mana Anda menargetkan sumber daya SharePoint seperti Web , ListItem dan ETC (disarankan) 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' ]))atau sebagai alternatif melalui metode rantai (alias antarmuka lancar):
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 - Di mana Anda membangun kueri istirahat (dan tidak ada model yang terlibat)
Contohnya menunjukkan cara membaca properti 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 ))Daftar contoh:
Bekerja dengan file
Bekerja dengan daftar dan daftar item
Rujuk bagian contoh untuk skenario lain
Dukungan untuk lingkungan SharePoint yang tidak standar saat ini sedang diimplementasikan. Saat ini didukung:
Untuk mengaktifkan otentikasi ke titik akhir tinggi GCC, tambahkan parameter environment='GCCH' saat memanggil ClientContext class dengan .with_user_credentials , .with_client_credentials , atau .with_credentials
Contoh:
from office365 . sharepoint . client_context import ClientContext
client_credentials = ClientCredential ( '{client_id}' , '{client_secret}' )
ctx = ClientContext ( '{url}' ). with_credentials ( client_credentials , environment = 'GCCH' )Daftar API yang didukung:
Karena API Outlook REST tersedia di Microsoft Graph dan titik akhir Outlook API, klien berikut tersedia:
GraphClient yang menargetkan versi Outlook API v2.0 ( lebih disukai saat ini, rujuk transisi ke Outlook REST API berbasis grafik Microsoft untuk perincian)OutlookClient yang menargetkan versi Outlook API v1.0 (tidak disarankan untuk penggunaan karena versi v1.0 sedang digunakan.)Microsoft Authentication Library (MSAL) untuk Python yang datang sebagai ketergantungan digunakan sebagai pustaka default untuk mendapatkan token untuk memanggil Microsoft Graph API.
Menggunakan Microsoft Authentication Library (MSAL) untuk Python
Catatan: Token akses diperoleh melalui aliran kredensial klien dalam contoh yang disediakan. Bentuk akuisisi token lainnya dapat ditemukan di sini: 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 )Tetapi dalam hal otentikasi API Microsoft Graph, perpustakaan yang sesuai dengan spesifikasi OAuth lainnya seperti Adal juga didukung.
Menggunakan Adal Python
Penggunaan
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 )Contohnya menunjukkan cara mengirim email melalui titik akhir Microsoft Graph.
Catatan: Token Akses diperoleh melalui aliran kredensial klien
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 ()Contoh & Skenario Tambahan:
Lihat bagian contoh untuk skenario lain
Referensi API Grafik OneDrive
Perpustakaan Otentikasi Microsoft (MSAL) untuk Python yang datang sebagai ketergantungan digunakan untuk mendapatkan token
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 Contoh ini menunjukkan cara menyebutkan dan mencetak URL drive yang sesuai dengan list available drives titik akhir
Catatan: Token Akses diperoleh melalui aliran kredensial klien
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 )Di mana
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 ()Contoh tambahan:
Lihat bagian Contoh OneDrive untuk contoh lebih lanjut.
Perpustakaan Otentikasi Microsoft (MSAL) untuk Python yang datang sebagai ketergantungan digunakan untuk mendapatkan token
Contoh ini menunjukkan bagaimana membuat tim baru di bawah grup yang sesuai untuk Create team
from office365 . graph_client import GraphClient
client = GraphClient ( acquire_token_func )
new_team = client . groups [ "{group-id}" ]. add_team (). execute_query_retry ()Contoh tambahan:
Lihat bagian contoh untuk skenario lain
Perpustakaan mendukung OneNote API dalam hal panggilan ke buku catatan, bagian, dan halaman OneNote pengguna dalam akun pribadi atau organisasi
Contoh: Buat halaman baru
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 () Contoh ini menunjukkan cara membuat tugas perencana baru yang sesuai untuk 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 ()Perpustakaan berikut akan diinstal saat Anda menginstal Perpustakaan Klien:
Python Ide Pycharm yang kuat dari Jetbrains .