杰瑞科技汇

SharePoint如何用Python交互?

Of course! Using Python with SharePoint is a very common and powerful way to automate tasks, manage content, and integrate data. Here’s a comprehensive guide covering the main methods, libraries, and code examples.

SharePoint如何用Python交互?-图1
(图片来源网络,侵删)

Why Use Python with SharePoint?

  • Automation: Automate repetitive tasks like uploading files, updating metadata, or creating sites.
  • Data Integration: Pull data from SharePoint lists into a pandas DataFrame for analysis or push data from other systems into SharePoint.
  • Content Management: Bulk manage documents, folders, and permissions.
  • CI/CD: Integrate SharePoint operations into your DevOps pipelines (e.g., deploying documentation).
  • Custom Solutions: Build custom web front-ends or backend services that interact with SharePoint.

The Main Approaches to Connect to SharePoint

There are three primary ways to interact with SharePoint using Python, each with its own strengths and use cases.

The SharePoint REST API (Most Common & Recommended)

This is the modern, standard way to interact with SharePoint. It's a RESTful API that you can call using standard HTTP methods (GET, POST, PATCH, DELETE). The Python requests library is perfect for this.

  • Pros:
    • No complex setup or dependencies beyond requests.
    • Works with both SharePoint Online and SharePoint On-Premises (2025+).
    • Full access to almost all SharePoint objects (sites, lists, libraries, items, users, etc.).
    • Well-documented and flexible.
  • Cons:
    • Requires building API endpoint URLs and handling authentication manually.
    • Can be verbose for complex operations.

The PnP (Patterns and Practices) Python Library

This is a community library that wraps the SharePoint REST API and provides a much more "Pythonic" and easier-to-use interface. It's the spiritual successor to the popular pnpjs library for JavaScript.

  • Pros:
    • Much simpler syntax: Abstracts away the raw API calls.
    • Rich functionality: Includes helpers for common tasks like uploading files, managing permissions, and working with search.
    • High-level abstractions: Makes it easy to work with sites, lists, and files.
  • Cons:
    • Adds another dependency to your project.
    • May not cover every single niche API call as directly as the raw REST API.

The Microsoft Graph API (The Modern Microsoft 365 API)

This is Microsoft's unified API for all its services in the cloud (SharePoint, Teams, OneDrive, Outlook, etc.). If you are working with SharePoint Online and also need to interact with other Microsoft 365 services, this is the best choice.

  • Pros:
    • Unified Access: One API to rule them all.
    • Modern and future-proof: Microsoft's primary focus for cloud development.
    • Access to SharePoint-specific features and also contextual data (like the user's Teams activity).
  • Cons:
    • Primarily for SharePoint Online (limited support for on-premises).
    • Some SharePoint-specific operations might have different endpoints or be less mature than in the native SharePoint REST API.

Prerequisites: Authentication

Before you can do anything, you need to authenticate. The method depends on your environment (SharePoint Online vs. On-Premises) and the approach you choose.

For SharePoint Online

The most common and recommended method is using Azure AD App Registration.

  1. Register an App in Azure AD:
    • Go to the Azure Portal -> Azure Active Directory -> App registrations -> New registration.
    • Give it a name (e.g., "SharePoint Python Script").
    • Choose "Accounts in this organizational directory only" (or "Any Azure AD directory..." for multi-tenant).
    • Click Register.
  2. Get Credentials:
    • From the app's overview page, copy the Application (client) ID and Directory (tenant) ID.
    • Go to Certificates & secrets -> New client secret. Give it a description and choose an expiry. Copy the Value of the secret. This value is only shown once!
  3. Grant API Permissions:
    • Go to API permissions -> Add a permission -> SharePoint.
    • Choose Application permissions (for server-to-server scenarios without a user).
    • Select Sites.FullControl.All (for full control over all site collections) or a more specific permission like Sites.ReadWrite.All.
    • Click Grant admin consent for your tenant.

For SharePoint On-Premises

You typically use App-Only Principal or Classic (User) Credentials. The requests_ntlm library is often used here to handle NTLM/Kerberos authentication.


Code Examples

Let's look at examples for each approach.

Setup: Install Necessary Libraries

# For the raw REST API approach
pip install requests
# For the PnP Python Library approach
pip install pnp
# For the Microsoft Graph API approach
pip install requests msal

Example 1: Using the SharePoint REST API with requests

This example connects to a SharePoint site, reads all items from a list, and uploads a file.

import requests
import json
from urllib.parse import quote
# --- Configuration ---
# Replace with your details
SHAREPOINT_SITE_URL = "https://yourtenant.sharepoint.com/sites/YourSite"
CLIENT_ID = "your-client-id-from-azure-ad"
CLIENT_SECRET = "your-client-secret-from-azure-ad"
LIST_NAME = "YourListName" # The name of your SharePoint list
# --- Authentication ---
# Get an access token using Azure AD
token_url = f"https://login.microsoftonline.com/{SHAREPOINT_SITE_URL.split('/')[2]}/oauth2/v2.0/token"
token_data = {
    'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'scope': f'{SHAREPOINT_SITE_URL}/.default'
}
response = requests.post(token_url, data=token_data)
access_token = response.json().get('access_token')
if not access_token:
    raise Exception("Could not get access token")
# --- API Headers ---
headers = {
    'Authorization': f'Bearer {access_token}',
    'Accept': 'application/json;odata=verbose' # For classic SharePoint API responses
}
# --- 1. Get all items from a list ---
# Note: Modern API uses odata=nometadata for simpler responses
list_endpoint = f"{SHAREPOINT_SITE_URL}/_api/web/lists/getbytitle('{LIST_NAME}')/items"
response = requests.get(list_endpoint, headers=headers)
response.raise_for_status() # Raise an exception for bad status codes
items = response.json()['d']['results']
print(f"Found {len(items)} items in the list '{LIST_NAME}':")
for item in items:
    print(f"  - ID: {item['ID']}, Title: {item['Title']}")
# --- 2. Upload a file to a Document Library ---
# Replace with your library and file path
LIBRARY_NAME = "Documents"
FILE_PATH = "C:/path/to/your/local/file.txt"
FILE_NAME = "file.txt"
# The SharePoint REST API endpoint for uploading files
upload_endpoint = f"{SHAREPOINT_SITE_URL}/_api/web/getfolderbyserverrelativeurl('{LIBRARY_NAME}')/files/add(url='{FILE_NAME}',overwrite=true)"
with open(FILE_PATH, 'rb') as f:
    # The file content goes in the body
    response = requests.post(upload_endpoint, headers=headers, data=f)
    response.raise_for_status()
print(f"\nSuccessfully uploaded '{FILE_NAME}' to '{LIBRARY_NAME}'.")
print("Response:", response.json())

Example 2: Using the PnP Python Library

This achieves the same tasks as the REST example but with much cleaner code.

from pnp import SharePoint, SharePointNode
# --- Configuration ---
# The PnP library handles authentication using the same Azure AD App credentials
SHAREPOINT_SITE_URL = "https://yourtenant.sharepoint.com/sites/YourSite"
CLIENT_ID = "your-client-id-from-azure-ad"
CLIENT_SECRET = "your-client-secret-from-azure-ad"
LIST_NAME = "YourListName"
LIBRARY_NAME = "Documents"
FILE_PATH = "C:/path/to/your/local/file.txt"
FILE_NAME = "file.txt"
# --- Authentication & Connection ---
# The library simplifies the connection process
sp = SharePointNode(
    site_url=SHAREPOINT_SITE_URL,
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET
)
sharepoint = sp.sharepoint
# --- 1. Get all items from a list ---
# The PnP library provides a simple property to access list items
list_obj = sharepoint.web.lists.get_by_title(LIST_NAME)
items = list_obj.items.get_all()
print(f"Found {len(items)} items in the list '{LIST_NAME}':")
for item in items:
    print(f"  - ID: {item.Id}, Title: {item.Title}")
# --- 2. Upload a file to a Document Library ---
# The PnP library has a high-level method for this
# It handles chunking for large files automatically
library = sharepoint.web.get_folder_by_server_relative_url(LIBRARY_NAME)
with open(FILE_PATH, 'rb') as f:
    library.upload_file(FILE_NAME, f)
print(f"\nSuccessfully uploaded '{FILE_NAME}' to '{LIBRARY_NAME}'.")

Example 3: Using the Microsoft Graph API

This example uses the msal (Microsoft Authentication Library) for Python to get a token and then call Graph API endpoints.

import requests
import msal
# --- Configuration ---
# Graph API has different scopes
TENANT_ID = "your-tenant-id-from-azure-ad"
CLIENT_ID = "your-client-id-from-azure-ad"
CLIENT_SECRET = "your-client-secret-from-azure-ad"
SITE_URL = "https://yourtenant.sharepoint.com/sites/YourSite"
LIST_NAME = "YourListName"
# --- Authentication ---
# Use MSAL to get a token for Microsoft Graph
authority = f"https://login.microsoftonline.com/{TENANT_ID}"
scope = ["https://graph.microsoft.com/.default"] # .default gives all application permissions
app = msal.ConfidentialClientApplication(
    client_id=CLIENT_ID,
    authority=authority,
    client_credential=CLIENT_SECRET
)
result = app.acquire_token_for_client(scopes=scope)
if "access_token" not in result:
    raise Exception("Could not acquire token: " + str(result.get("error")))
access_token = result['access_token']
# --- API Headers ---
headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/json'
}
# --- 1. Get all items from a list ---
# Graph API uses a different endpoint structure
# First, get the site ID from its URL
site_id = f"root:/sites/{SITE_URL.split('/')[-3]}/{SITE_URL.split('/')[-2]}"
# Then, get the list by its name
list_response = requests.get(
    f"https://graph.microsoft.com/v1.0/sites/{site_id}/lists/{LIST_NAME}",
    headers=headers
)
list_response.raise_for_status()
list_id = list_response.json()['id']
# Finally, get the items from the list
items_response = requests.get(
    f"https://graph.microsoft.com/v1.0/sites/{site_id}/lists/{list_id}/items",
    headers=headers
)
items_response.raise_for_status()
items = items_response.json()['value']
print(f"Found {len(items)} items in the list '{LIST_NAME}':")
for item in items:
    print(f"  - ID: {item['id']}, Title: {item['fields']['title']}")
# --- 2. Upload a file to a Document Library ---
# Graph API uses a simple PUT request to the drive endpoint
# First, get the drive ID for the document library
drive_response = requests.get(
    f"https://graph.microsoft.com/v1.0/sites/{site_id}/drive",
    headers=headers
)
drive_response.raise_for_status()
drive_id = drive_response.json()['id']
# Then, upload the file
with open(FILE_PATH, 'rb') as f:
    upload_response = requests.put(
        f"https://graph.microsoft.com/v1.0/drives/{drive_id}/root:/{FILE_NAME}:/content",
        headers=headers,
        data=f
    )
    upload_response.raise_for_status()
print(f"\nSuccessfully uploaded '{FILE_NAME}' using Microsoft Graph.")

Summary: Which One Should You Choose?

Feature SharePoint REST API PnP Python Library Microsoft Graph API
Ease of Use Low (manual URL/JSON handling) High (Pythonic, abstracted) Medium (similar to REST, but different endpoints)
Dependencies requests only pnp requests, msal
Flexibility Highest (access to everything) High (covers most common needs) High (unified across M365)
Best For Full control, niche operations, on-premises Quick automation, common tasks, developers who prefer simplicity Cloud-only projects, integrating with other M365 services (Teams, etc.)
Recommendation Start here for learning and maximum control. Recommended for most automation scripts. The modern standard for cloud-centric development.
分享:
扫描分享到社交APP
上一篇
下一篇