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 Portal에서 찾을 수 있습니다.
액세스 단계 :
ClientContext
클라이언트는 지원되는 버전 목록 인 레거시 SharePoint REST 및 OneDrive for Business REST API에 대한 지원을 제공합니다.
다음 인증 흐름이 지원됩니다.
이 인증 방법은 SharePoint 온 프레미스에서 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
로컬 브라우저를 통해 대화식으로 로그인합니다
전제 조건 :
Azure Portal에서 "모바일 및 데스크탑 응용 프로그램"의 ridirect 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
- 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' ]))
또는 메소드 체인을 통해 (일명 유창한 인터페이스) :
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
- REST 쿼리를 구성하는 곳 (및 모델이 없음)
예제는 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 High Endpoints에 대한 인증을 활성화하려면 .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 Graph와 Outlook API 엔드 포인트 모두에서 사용할 수 있으므로 다음 클라이언트를 사용할 수 있습니다.
v2.0
버전을 대상으로하는 GraphClient
(요즘 바람직한 경우 , Microsoft 그래프 기반 Outlook REST API로의 전환을 참조하십시오)v1.0
버전을 대상으로하는 OutlookClient
( v1.0
버전이 더 이상 사용되지 않아서 권장되지 않습니다.)종속성으로 제공되는 Python 용 Microsoft Authentication Library (MSAL)는 Microsoft Graph API를 호출 할 토큰을 얻기 위해 기본 라이브러리로 사용됩니다.
Python에는 MSAL (Microsoft Authentication Library) 사용
참고 : Access Token은 제공된 예제에서 클라이언트 자격 증명 흐름을 통해 획득됩니다. 다른 형태의 토큰 획득은 여기에서 찾을 수 있습니다 : 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 사양 호환 라이브러리도 지원됩니다.
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 그래프 엔드 포인트를 통해 이메일을 보내는 방법을 보여줍니다.
참고 : Access Token은 클라이언트 자격 증명 흐름을 통해 인수됩니다.
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을 열거하고 인쇄하는 방법을 보여줍니다.
참고 : Access Token은 클라이언트 자격 증명 흐름을 통해 인수됩니다.
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
.