wp-post-automation/package/wp.py
2024-10-03 08:32:03 +09:00

43 lines
1.2 KiB
Python

import os
from dotenv import load_dotenv
import json
import requests
from urllib.parse import urljoin
from datetime import datetime
# .env 파일에서 API 키 로드
load_dotenv(r'./.env.dev')
wp_url = os.getenv('WP_URL')
wp_usr = os.getenv('WP_USERNAME')
wp_key = os.getenv('WP_API_KEY')
status = 'draft' # 즉시발행 publish, 임시저장 draft
# slug = 'input your slug'
title = '파이썬 자동포스팅'
content = 'html 호출 연동 필요.' # 연결만하면됨 테스트 완료.
category_id = [2] # 카테고리 아이디
# tag_ids = [21] #태그아이디
media_id=None #이미지 업로드를 제외 None
payload = {
"status": status,
"title": title,
"content": content,
"date": datetime.now().isoformat(), # YYYY-MM-DDTHH:MM:SS
"categories": category_id
}
if media_id is not None:
payload['featured_media'] = media_id
result = requests.post(urljoin(wp_url, "wp-json/wp/v2/posts"),
data=json.dumps(payload),
headers={'Content-type': "application/json"},
auth=(wp_usr, wp_key))
if result.ok:
print(f"성공 code:{result.status_code}")
else:
print(f"실패 code:{result.status_code} reason:{result.reason} msg:{result.text}")