Drupal REST API 自動將 JSON 格式的資料匯入 Drupal
2025-05-09
標籤: Drupal API
廣告
import requests
import json
import base64
from urllib.parse import urljoin
# Configuration
DRUPAL_URL = "http://example.com" # Drupal site URL
USERNAME = "admin" # Drupal username
PASSWORD = "password" # Drupal password
JSON_FILE = "exported_data.json" # Path to JSON file with exported data
# Encode credentials for HTTP Basic Authentication
credentials = f"{USERNAME}:{PASSWORD}"
auth_header = {
"Authorization": f"Basic {base64.b64encode(credentials.encode()).decode()}"
}
def load_json_data(file_path):
"""Load JSON data from file."""
try:
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
except FileNotFoundError:
print(f"Error: File {file_path} not found.")
return []
except json.JSONDecodeError:
print("Error: Invalid JSON format.")
return []
def check_existing_title(title):
"""Check if a node with the given title already exists."""
url = urljoin(DRUPAL_URL, "/node")
params = {"_format": "json", "title": title}
headers = {
"Content-Type": "application/json",
**auth_header
}
try:
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
nodes = response.json()
return len(nodes) > 0 # Return True if title exists
except requests.RequestException as e:
print(f"Error checking title '{title}': {e}")
return False
def create_node(data):
"""Create a new node in Drupal via REST API."""
url = urljoin(DRUPAL_URL, "/entity/node?_format=json")
headers = {
"Content-Type": "application/json",
**auth_header
}
# Prepare node data
node_data = {
"type": [{"target_id": "article"}],
"title": [{"value": data.get("title", "")}],
"body": [{"value": data.get("content", ""), "format": "basic_html"}]
}
try:
response = requests.post(url, headers=headers, json=node_data)
response.raise_for_status()
print(f"Successfully created node: {data.get('title')}")
return response.json()
except requests.RequestException as e:
print(f"Error creating node '{data.get('title')}': {e}")
return None
def main():
"""Main function to import JSON data into Drupal."""
# Load JSON data
data_list = load_json_data(JSON_FILE)
if not data_list:
print("No data to import.")
return
# Process each item
for item in data_list:
title = item.get("title", "")
if not title:
print("Skipping item with no title.")
continue
# Skip if title already exists
if check_existing_title(title):
print(f"Skipping existing title: {title}")
continue
# Create new node
create_node(item)
if __name__ == "__main__":
main()
使用說明
此 Python 腳本透過 Drupal REST API 自動將 JSON 格式的資料匯入 Drupal,適用於從其他平台(如 WordPress)搬站至 Drupal。只要資料以 JSON 格式匯出,腳本即可處理,並確保相同標題的內容不會重複匯入。
功能特色
- 自動化匯入:從 JSON 文件讀取資料並透過 REST API 匯入 Drupal。
- 避免重複:檢查標題是否已存在,跳過重複內容。
- 跨平台適用:支援任何可匯出 JSON 的平台(如 WordPress、Joomla),只需確保 JSON 結構包含
title
和content
欄位。 - HTTP Basic Authentication:使用簡單的認證方式,易於設置。
前置條件
- Drupal 環境:
- 已啟用
rest
、serialization
和basic_auth
模組。 - 配置 REST API 支援節點創建(參考前述範例的
services.yml
或資源配置)。 - 用戶具有「創建 article 內容類型」和「訪問 RESTful 資源」權限。
- JSON 資料格式:
- 範例 JSON 結構:
json [ { "title": "Article Title 1", "content": "This is the content of article 1." }, { "title": "Article Title 2", "content": "This is the content of article 2." } ]
- 必須包含
title
欄位,content
為可選(對應 Drupal 的body
欄位)。 - Python 環境:
- 安裝必要的庫:
requests
bash pip install requests
使用步驟
- 準備 JSON 文件:
- 從來源平台(如 WordPress)匯出資料為 JSON 格式,保存為
exported_data.json
。 - 確保 JSON 結構與上述範例相容。
- 配置腳本:
- 修改腳本頂部的配置:
DRUPAL_URL
:你的 Drupal 網站 URL(如http://example.com
)。USERNAME
和PASSWORD
:Drupal 管理員帳戶的用戶名和密碼。JSON_FILE
:JSON 文件的路徑。
- 執行腳本:
bash python import_script.py
- 腳本會逐一處理 JSON 中的項目,檢查標題是否存在,若不存在則創建新文章。
- 檢查結果:
- 腳本會輸出每篇文章的處理狀態(成功或跳過)。
- 登錄 Drupal 後台,檢查「內容」頁面確認匯入的文章。
適用場景
- WordPress 搬站:使用 WordPress 外掛(如 WP All Export)匯出文章為 JSON,然後使用此腳本匯入 Drupal。
- 其他 CMS 搬站:任何支持 JSON 匯出的 CMS(如 Joomla、Ghost)均可使用,只需調整 JSON 欄位映射。
- 批次內容匯入:快速將大量文章或頁面匯入 Drupal,無需手動操作。
注意事項
- 安全性:確保使用 HTTPS 保護 API 請求,密碼不會明文傳輸。
- 錯誤處理:腳本包含基本錯誤處理(如檔案不存在、JSON 格式錯誤、API 請求失敗),但建議檢查輸出日誌。
- 欄位自定義:若需要匯入其他欄位(如分類、標籤),修改
create_node
函數中的node_data
,添加對應欄位(如"field_tags": [{"target_id": "tag_id"}]
)。 - 效能:大量資料匯入可能較慢,建議分批處理或使用緩存清除(
drush cr
)。 - 認證:HTTP Basic Authentication 適合開發環境,生產環境建議使用 OAuth 或 JWT。