概要
毎回ブラウザ認証する or トークンが期限切れになったらブラウザ認証は面倒なので refresh_token を使って認証トークンを再取得できます
環境
- macOS 15.5
- Python 3.12.11
- google-api-python-client 2.174.0
Python スクリプト
-
vim app.py
import os
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
class BloggerClient:
# スコープ(Blogger のフルアクセス)
SCOPES = ["https://www.googleapis.com/auth/blogger"]
# 対象のブログID
BLOG_ID = "1234567890"
def __init__(
self, client_secrets_file="client_secrets.json", token_file="token.json"
):
self.client_secrets_file = client_secrets_file
self.token_file = token_file
self.creds = self._authenticate()
self.service = self._build_service()
def _authenticate(self):
# 認証情報の取得
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", self.SCOPES)
if not creds.valid:
if creds.expired and creds.refresh_token:
# トークンが有効期限切れの場合は更新
creds.refresh(Request())
else:
# トークンが無効な場合は再認証
os.remove("token.json")
return self._authenticate()
else:
# token.json がない場合はブラウザを使って初回認証する
flow = InstalledAppFlow.from_client_secrets_file(
"client_secrets.json", self.SCOPES
)
creds = flow.run_local_server(port=0, access_type="offline")
with open("token.json", "w") as token:
token.write(creds.to_json())
return creds
def _build_service(self):
# Blogger API サービスのビルド
return build("blogger", "v3", credentials=self.creds)
def post_to_blog(self, title, content) -> str:
# ブログに投稿する
body = {
"kind": "blogger#post",
"title": title,
"content": content,
}
# 投稿の実行
result = self.service.posts().insert(blogId=self.BLOG_ID, body=body).execute()
return result["url"]
ちょっと解説
ポイントは _authenticate メソッドです
token.json がある場合はそれを再利用しますが token.json にあるトークンがすでに期限切れの場合には refresh メソッドをコールします
こうすることで毎回ブラウザで認証する必要がなくなります
最後に
OAuth2.0 は大抵の場合 refresh_token があるので CLI などの環境ではこれを使ってトークンを更新するようにしましょう
0 件のコメント:
コメントを投稿