GoogleAppEngine再入門(3) -Datastore API 2-

前回:GoogleAppEngine再入門(2) -Datastore API 1- - souta-bot log
DatastoreAPIの続き

動的なproperty作成

  • db.Modelを継承したdb.Expandoを使えばpropertyとして定義していない形式のデータも格納できる

早速日経ソフトウェア2009/1月号リスト5のコードを写経

# -*- coding: utf-8 -*-
from google.appengine.ext import db
import datetime

class Song(db.Expando):
    title = db.StringProperty()

songs = Song.all()

if songs.count() == 0:
    dragonfly = Song(title='Dragonfly',
                     author='Takashi Matsuo',
                     publish_date='yesterday',
                     rating=5.0)
    masterpiece = Song(title='The Sound of Silence',
                       author='Simon Garfunkel',
                       publish_date=datetime.datetime(1968, 6, 15))
    dragonfly.last_minute_note=db.Text(
        'This song could be another masterpiece!')
    db.put([dragonfly, masterpiece])
    songs = Song.all()

print "Content-Type: text/html\n"
print "<html>"
for song in songs:
    print song.title
    print "<br />"
    print "<ul>"

    #dynamic_propertiesメソッドでプロパティのリストを取得
    for prop_name in song.dynamic_properties():
        #getattr関数でアトリビュートの値を取得
        print "<li>%s: %s</li>" % (prop_name, getattr(song, prop_name))
    print "</ul>"
print "</html>"

実行結果


ヽ(*´∀`)ノ キャッホーイ!!

動的に設定したpropertyの削除
del song.author
song.put()

Datastoreの編集

作成したentityを削除するのに、いちいちdb.delete()とかをやるのは面倒なのでSDK Consoleを使う

  1. GoogleAppEngineLauncherからCmd-KでSDK Consoleを開く
  2. Entity Kindから編集したいデータモデル(ここではSong)を選択しList Entitiesボタン
  3. 削除したいentityをチェックし、Deleteボタン

それぞれのentityの編集も可能
参考:http://d.hatena.ne.jp/CortYuming/20081129/p2

トランザクション処理

RDBとは異なるので注意

用語
  • entityには親となるentity、子となるentityを指定できる
  • 一連の親子群を「entity group」と呼ぶ
  • entity groupの頂点を「root」と呼ぶ
  • あるentityの全ての親entityを「ancestors」と呼ぶ
  • rootから末端entityの一連の連なりを「path」と呼ぶ
トランザクション処理実行の際の注意点

なんか実例が無いとモヤモヤしたままだが、それはおいおい

次回:GoogleAppEngine再入門(4) -RSS Readerを作る- - souta-bot log