Moonie

구글 블로그스팟 api 하는 방법 본문

공부/기타 다른 공부

구글 블로그스팟 api 하는 방법

Moonie' 2024. 10. 16. 17:47
반응형

 

1. API key 발급

https://console.cloud.google.com/

 

Google 클라우드 플랫폼

로그인 Google 클라우드 플랫폼으로 이동

accounts.google.com

홈페이지 를 들어간 후 좌측 상단 네모 박스를 눌러 프로젝트 선택 화면에서 새 프로젝트를 클릭한다.

 

 

 

새 프로젝트 화면에서 원하는 프로젝트 이름을 설정한다.

 

블로거 api 를 검색한다.

 

검색후 '사용' 버튼을 클릭한다.

설치 완료 후 'OAuth 동의화면' 에서 '외부'를 선택한다.

만든 후 앱정보, 개발자 연락처 정보를 입력한다.

 

범위에서 '범위 추가 또는 삭제'를 선택한다.

그 후 모든 범위에 대하여 체크한다.

 

'+ ADD USERS'를 선택 후 본인 계정을 입력한다.

'사용자 인증 정보' 메뉴에서 'OAuth 클라이언트 ID' 를 선택하여

'애플리케이션 유형'명을 입력 이름은 원하는 것으로 입력한다.

 

구글 블로거 API를 쓰기위해서는 google drive 키 발급도 있어야 한다.

Google Drive Api에 검색하고 '사용'버튼을 눌러 추가하여 준다.

 

파이썬 구글 블로거 업로드

업로드를 위하여 python 라이브러리르 설치한다.

pip install oauth2client
pip install google-api-python-client
pip install google-auth-oauthlib

 

최종적으로 아래 코드를 입력하고 실행한 후 전부 허용(구글드라이브, 구글 블로거) 하면 게시가 되는 것을 확인 할 수 있다.

(api key는 json으로 받아 경로에 추가해줘야한다.)

import sys
import os
import pickle
from oauth2client import client
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

BLOG_ID = '1752041361745683828'  # blogname
SCOPES = ['https://www.googleapis.com/auth/blogger', 'https://www.googleapis.com/auth/drive.file']

def get_blogger_service_obj():
    creds = None
    if os.path.exists('auth_token.pickle'):
        with open('auth_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.json', SCOPES)
            creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('auth_token.pickle', 'wb') as token:
                pickle.dump(creds, token)
    blog_service = build('blogger', 'v3', credentials=creds)
    drive_service = build('drive', 'v3', credentials=creds)

    return drive_service, blog_service

drive_handler, blog_handler = get_blogger_service_obj()

keyword = '테스트'
blogger_title = '안녕하세요, 테스트입니다.'
content = '안녕하세요, 테스트입니다.'
#content += '<meta content="0; URL='+str(blogger_redirect_url)+'" http-equiv="Refresh"></meta>'
data = {
    'content': content,
    'title': blogger_title,
    'labels': keyword,
    'blog': {
        'id': BLOG_ID,  # The identifier of the Blog that contains this Post.
    },
}
posts = blog_handler.posts()
res = posts.insert(blogId=BLOG_ID, body=data, isDraft=False, fetchImages=True).execute()
res

 

이미지를 업로드 하는 방식은 아쉽게도 local 경로 파일에서 업로드 하는 방법은 없다고 한다.

 

import sys
import os
import pickle
from oauth2client import client
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

BLOG_ID = '1752041361745683828'  # blogname
SCOPES = ['https://www.googleapis.com/auth/blogger', 'https://www.googleapis.com/auth/drive.file']

def get_blogger_service_obj():
    creds = None
    if os.path.exists('auth_token.pickle'):
        with open('auth_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.json', SCOPES)
            creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('auth_token.pickle', 'wb') as token:
                pickle.dump(creds, token)
    blog_service = build('blogger', 'v3', credentials=creds)
    drive_service = build('drive', 'v3', credentials=creds)

    return drive_service, blog_service

drive_handler, blog_handler = get_blogger_service_obj()

keyword = '테스트'
blogger_title = '테스트, 테스트입니다.'

imagepath = 'https://www.google.com/imgres?q=%EA%B0%95%EC%95%84%EC%A7%80&imgurl=https%3A%2F%2Fflexible.img.hani.co.kr%2Fflexible%2Fnormal%2F960%2F960%2Fimgdb%2Fresize%2F2019%2F0121%2F00501111_20190121.JPG&imgrefurl=https%3A%2F%2Fwww.hani.co.kr%2Farti%2Fanimalpeople%2Fcompanion_animal%2F879191.html&docid=WPGXKyyFEdDzjM&tbnid=GGtQzKvAToms7M&vet=12ahUKEwjSot6FwZKJAxXnja8BHcpMDOQQM3oECBgQAA..i&w=960&h=960&hcb=2&ved=2ahUKEwjSot6FwZKJAxXnja8BHcpMDOQQM3oECBgQAA'  # 이미지 URL 주소

content = '<b>필수로 설치해야될 파이썬 패키지 리스트</b></p>'
# content += '<div style="text-align: center;">'
content += '<div class="separator" style="clear: both; text-align: center;">'
content += '<a href="'+imagepath+'" imageanchor="1" style="margin-left: 1em; margin-right: 1em;">'
content += '<img border="0" data-original-height="492" height="492" src="'+imagepath+'" width="492" /></a></div><br /><div><br /></div>'

# content += '<meta content="0; URL='+str(blogger_redirect_url)+'" http-equiv="Refresh"></meta>'

data = {
    'content': content,
    'title': blogger_title,
    'labels': keyword,
    'blog': {
        'id': BLOG_ID,  # The identifier of the Blog that contains this Post.
    },
}

posts = blog_handler.posts()
res = posts.insert(blogId=BLOG_ID, body=data, isDraft=False, fetchImages=True).execute()
res
반응형
Comments