BREAKING NEWS

2017/06/19

PythonでGoogle Blogger APIを使う(その1:Pythonのサンプルコードの紹介)

PythonでGoogle Blogger APIを使う(その1:Pythonのサンプルコードの紹介)

この記事のまとめ
  • PythonでBlogger用Google APIを使うサンプルコードの紹介
背景

Bloggerをプログラムによって投稿できないものかと画策しており、いろいろ調べた結果、Blogger用のAPIが使えそうだったので、PythonでBlogger APIを使う方法を私自身の備忘録としても記載しておきます。

少し説明が長いので4回に分けて説明します。

  1. Pythonのサンプルコードの紹介 ← 今回はここ
  2. サンプルコードの概要説明
  3. Python用Google APIのインストール
  4. OAuth認証に必要な情報の取得

なおここでは、WindowsベースでPythonを使うことを前提とします。また、Pythonの導入方法については、ここでは行いません。

今回は、まずはとりあえずサンプルコードだけ載せておきます。

サンプルコード

下記はBloggerの記事をAPIから投稿するコードです。

from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
from oauth2client        import tools,file
import argparse
import httplib2
import os
import sys
 
def main(argv):
 
    # flowオブジェクトの生成
    client_id     = '{自身のClient ID}'
    client_secret = '{自身のClient Secret}'
    scope         = 'https://www.googleapis.com/auth/blogger'
    redirect_uri  = 'urn:ietf:wg:oauth:2.0:oob'
    flow          = OAuth2WebServerFlow(client_id=client_id,
                                        client_secret=client_secret,
                                        scope=scope,
                                        redirect_uri=redirect_uri)
 
    # strageオブジェクトの生成、読み込み
    storage     = file.Storage(__file__ + '.dat') # 認証資格情報の保存ファイル名
    credentials = storage.get()                   # 認証資格情報の読み込み
 
    # 認証資格情報の取得(保存済みの資格情報がない場合)
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage)
 
    http = credentials.authorize(http = httplib2.Http())
 
    service = build('blogger', 'v3', http=http)
    posts   = service.posts()
    body    = {
                  "kind": "blogger#post",
                  "id": "{自身のブログID}",
                  "title": "posted via python",
                  "content":"<div>hello world test</div>"
              }
    insert    = posts.insert(blogId='{自身のブログID}', body=body)
    posts_doc = insert.execute()
 
    print posts_doc
 
 
if __name__ == '__main__':
    main(sys.argv)

以上です。とりあえず今回はここまで。

次回は、サンプルコードの概要説明を行います。

最後まで読んでいただき、ありがとうございます。




ブログランキング・にほんブログ村へ  ← 気に入っていただければ応援ポチをお願いします!

Share this:

 
Copyright © 2014 hassiweb. Designed by OddThemes