概要
前回は記事を投稿する方法を紹介しました
今回は更新する方法を紹介します
環境
- macOS 15.5
- Python 3.12.11
- google-api-python-client 2.174.0
Python スクリプト
-
vim app.py
import os
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# スコープ(Blogger のフルアクセス)
SCOPES = ["https://www.googleapis.com/auth/blogger"]
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
else:
flow = InstalledAppFlow.from_client_secrets_file("client_secrets.json", SCOPES)
creds = flow.run_local_server(port=8080, access_type="offline")
with open("token.json", "w") as token:
token.write(creds.to_json())
# 以降のコードで自動リフレッシュ対応済み
service = build("blogger", "v3", credentials=creds)
# 対象のブログID
blog_id = "1234567890"
# ブログの一覧を取得したい場合は以下のコードを使用
# 対象ブログの取得(複数ある場合はリストされる)
# blogs = service.blogs().listByUser(userId='self').execute()
# for blog in blogs['items']:
# print(f"Blog ID: {blog['id']}, Title: {blog['name']}")
#
# blog_id = blogs['items'][0]['id'] # 1つ目のブログを使う
body = {
"kind": "blogger#post",
"title": "テスト投稿",
"content": "<p>これは Python からの Blogger API を使ったテスト投稿です。</p>",
}
# 投稿の実行
result = service.posts().insert(blogId=blog_id, body=body).execute()
print(f"Post published: {result['url']}")
# 投稿IDを取得
post_id = result["id"]
body = {
"kind": "blogger#post",
"title": "テスト投稿(更新)",
"content": "<p><b>これは Python からの Blogger API を使ったテスト投稿です。</b></p>",
}
# 投稿の更新
result = service.posts().update(blogId=blog_id, postId=post_id, body=body).execute()
print(f"Post updated: {result['url']}")
動作確認
-
pipenv run python app.py
記事が更新されていることを確認しましょう
最後に
投稿した記事に付与される permalink は Blogger API v3 では更新できないので GUI から手動でやるしかないようです
0 件のコメント:
コメントを投稿