めも帖

「めも帖」代わりにダラダラと書いていったり、めもしたりしているだけです。

Spreadsheets Data APIを使ってGoogle App Engineのデータストアに登録

Googleドキュメントは、ネット上にエクセルのファイルがある感じで使える、だけじゃなく色々なAPIが用意されています。APIがあるということは、聞いて知っていたのですが、最近初めて使いました。

使ってみた理由は、GoogleAppEngineを利用している最中に感じた事です。GoogleAppEgineでの開発をしてみると、マスターデーターをまとめて用意したい場合が出てきたときに、一気にデーターを登録する方法が標準では用意されていません。そこで、どうしたものか?と考えてみると、Googleドキュメントからデーターを流し込むという方法が紹介されている事があり、試してみる事にしました。

ライブラリ

APIを利用するには、ライブラリを利用します。ライブラリは、「gdata-python-client - Google Data APIs Python Client Library - Google Project Hosting」にあります。よく見ると、JAVAJavaScript、.NET、PHP向けのライブラリがあります。また、Googleドキュメントだけではなく、GoogleカレンダーGoogle Analytics向けのライブラリもあります。
ライブラリは、実行ファイルと同じ場所に置きました

ファイルの用意

Googleドキュメントでファイルを用意します

ファイルのURL

https://spreadsheets.google.com/ccc?key=keyword
Googleドキュメントファイルを開くとURLが上記のようになっています。
keywordの部分を利用します

実行してみる

実行してみると空だったデータストアに

Googleドキュメントで用意した値が入ります

実際のファイル

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from django.utils import simplejson

import gdata.spreadsheet.text_db
import gdata.service
import atom.service
import gdata.spreadsheet
import atom
import gdata.spreadsheet.service
import gdata.urlfetch

# model
from Facility import *

class View:
	layout_file = 'layout.html'
	view_dir    = '../views/test/'
	layout = {'title':'sets','header':'header.html','footer':'footer.html',}

class MainHandler(webapp.RequestHandler):
	def get(self):
		email    = 'xxxxx@gmail.com'
		password = 'xxxxx'
		gd_client = gdata.spreadsheet.service.SpreadsheetsService()
		gd_client.email    = email 
		gd_client.password = password 
		gd_client.ProgrammaticLogin()

		key  = 'xxxxxxxxx'
		feed = gd_client.GetWorksheetsFeed(key)

		# ドキュメントの存在
		# シートの存在
		for entry in feed.entry:
			if entry.title.text == 'シート1':
				current_worksheet_title = entry.title.text
				current_worksheet_id = entry.id.text.split('/')[-1]
			else:
				raise ValueError('sheet not found')

		# 行ごと
		feed = gd_client.GetListFeed(key, current_worksheet_id)
		for entry in feed.entry:
			name    = entry.custom['name'].text
			address = entry.custom['address'].text
			db = Facility(name=name)
			db.address = address
			db.put()

		#data = {}
		#data['title']  = 'test'
		#View.layout['title']   = 'test'
		#View.layout['content'] = View.view_dir + 'index.html'

		#params = {'layout':View.layout, 'data':data}
		#filepath = os.path.join(os.path.dirname(__file__), 'layouts', View.layout_file)
		#html = template.render(filepath, params)
		#self.response.out.write(html)

def main():
	application = webapp.WSGIApplication(
				[
					('/',       MainHandler),
				], debug=True)
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
	main()
else:
	print 'error'