0. Todo
- Google Cloud 프로젝트 생성
- Blogger API 사용 설정
- OAuth 클라이언트 ID 생성
- Python으로 Blogger 서비스 연동하기
- Python으로 Blog 발행하기
1. Google Cloud 프로젝트 생성
① Google Cloud 계정 생성 (https://cloud.google.com/)
② Google Cloud Console로 이동 (https://console.cloud.google.com/)
③ 프로젝트 생성
2. Blogger API 사용 설정
① API 라이브러리 페이지로 이동 (API 및 서비스 → 라이브러리)
② Blogger 검색
③ Blogger API 사용 설정
이미 사용중이라 아래와 같이 '관리'라 나오지만 원래는 '사용'이라는 버튼이 있다.
3. OAuth 클라이언트 ID 생성
① 사용자 인증 정보 페이지로 이동 (API 및 서비스 → 사용자 인증 정보)
② OAuth 클라이언트 ID 생성
③ OAuth 클라이언트 다운로드
적당한 파일명으로 JSON 파일을 다운받아 적당한 경로에 위치시킨다.
(예: project/blog/client_secrets.json)
4. Python으로 Blogger 서비스 연동하기
① google-api-python-client 모듈 설치 (https://github.com/googleapis/google-api-python-client)
pip install google-api-python-client
② Blogger 서비스 연동
- CLIENT_SECRET = 다운받은 OAuth 클라이언트 JSON 파일 경로
- SCOPES = Blogger API에 접근하기 위한 OAuth Scope
(다른 서비스 Scope는 링크 참고)
import pickle
from pathlib import Path
from googleapiclient import discovery
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
CLIENT_SECRET = 'blog/client_secrets.json' # OAuth 클라이언트 json 파일 경로
SCOPES = ['https://www.googleapis.com/auth/blogger'] # Blogger OAuth Scope
def get_blogger_service_obj():
creds = None
if Path("auto_token.pickle").exists():
with open('auto_token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET, SCOPES)
creds = flow.run_local_server(port=0)
with open('auto_token.pickle', 'wb') as token:
pickle.dump(creds, token)
return discovery.build('blogger', 'v3', credentials=creds)
5. Python으로 Blog 발행하기
① Blogger 서비스 통해 blog 발행
- blog_id는 Blogger 생성 후 url에서 확인 가능 (https://www.blogger.com/blog/posts/<blog_id>)
- API 명세는 링크 참고
def blog_posting(blog_id, title, content, hashtags, draft=False):
blogger_service = get_blogger_service_obj()
posts = blogger_service.posts()
data = {
'title': title,
'content': content,
'labels': hashtags,
'blog': {
'id': blog_id
}
}
response = posts.insert(blogId=blog_id,
body=data,
isDraft=draft,
fetchImages=True).execute()
print("printing the page id:", response['id'])
OpenAI(ChatGPT) API로 블로그 발행하기
반응형