2008年9月19日金曜日

Uploading index definitions Error


何日かぶりに appcfg.py update xxxx/ で更新しようとしたところ以下のエラーで先に進まなくなってしまった。
タイミングとして新しいイメージファイルをいくも追加したので、それが原因かと思ったが、そうではないらしい。

Uploading index definitions.
Error 400: --- begin server output ---
Building a composite index failed: ApplicationError: 3
--- end server output ---

Issue 287:Explosion with >100 indexes


To vacuum your indexes: 
1. Create a backup of your index.yaml specification
2. Remove the definitions of the indexes in Error from your index.yaml file
3. Run appcfg.py vacuum_indexes your_app_dir/
4. Replace the modified version of your index.yaml file with the original
5. Run appcfg.py update your_app_dir/


を参考に まず index.yaml をクリアしてから vacuum すると、

This index is no longer defined in your index.yaml file.

ancestor: true
kind: Timeline
properties: []

Are you sure you want to delete this index? (N/y/a): y

ときかれるので、N として、いかにも不要そうな複合インデックスをいくつか削除して
appcfg.py vacuum_indexes your_app_dir/

にて今度は Y にて削除した。
いくつも削除したため、ダッシュボードでみると index の delete のタスクが走りだした。このタスク中に appcfg.py update xxxx/ すると
Server Error (500) A server error has occured.
となる。しばらく、時間をおいたところ無事 update できたが、その直後から今度はindex 作成のタスクがいくつも走りだした。




http://code.google.com/appengine/docs/datastore/queriesandindexes.html#Big_Entities_and_Exploding_Indexes

To handle "Error" indexes, first remove them from your index.yaml file and run appcfg.py vacuum_indexes. Then, either reformulate the index definition and corresponding queries or remove the entities that are causing the index to "explode." Finally, add the index back to index.yaml and run appcfg.py update_indexes.

2008年9月13日土曜日

Google Visualization API その2


Visualization APIを用いたプログラミング 
を参考に SpreadSheet からの Timeline の描画を行なってみた


Chart API だとすぐにぶつかるデータ数の壁をあっさりクリアしてしまった。
おそるべき JavaScript 。


・メモ
- spreadsheet は Share Anyone can this document WITHOUT LOGGING IN
 にしておくこと
- packages:["annotatedtimeline"]
 にSpreadSheet から 123.4 のように少数点付きの値を
 データとして与える場合 123.*100/100 のように一度 乗算して除算しないとなぜかうまくいか
 なかった。 ( javascript を理解していない? ためか  これには苦労した)
-  query.setQuery("select C, J from `Sheet 1` order by C");
 Sheet 1 を Sheet 2 に変えても、先頭のシートしか参照できない。 要調査

2008年9月12日金曜日

Google Visualization API


Google Visualization API
Gallery

Google Finance で使用されているものが登録されていた
さっそく Google App Engine と組み合わせ、使用したところ動作した
けれども、どうもデータの表示範囲のスクロールがなぜかうまくいかなかった。
原因はデータのラインの本数で、折れ線グラフが1本だけだと、下部分の
スクロール機能が動作しない仕様らしい。




2008年9月8日月曜日

Google Chart API で日本語

日本語を使用するには urllib.quote() 
u' 日本語'  はNG

import urllib

chart_ttile = '日本語'

      url2 = '<img src="http://chart.apis.google.com/chart?'
      url2+= 'chs=600x200'
      url2+= '&chtt=' + urllib.quote(chart_title)


Memo

2008年9月7日日曜日

Timeout Error

GAE で今まで動作していたアプリが動作しなくなった。

TemplateSyntaxError: Caught an exception while rendering:

テンプレートが重いのが問題かと 表示内容をけづっていったところ
動作したり、しなかったり。

  File "/base/python_lib/versions/1/google/appengine/api/datastore.py", line 1627, in _ToDatastoreError
raise errors[err.application_error](err.error_detail)
Timeout
同様の現象の報告もあり、様子をみることに。

http://groups.google.com/group/google-appengine/browse_thread/thread/53e7e0a34f3bec89/37b2a5a033ee0ac0?hl=en&lnk=gst&q=timeout+error#37b2a5a033ee0ac0

つい先日も  login: admin  の設定の URL ではログインできなかったが、翌日は復活していた。

2008年9月5日金曜日

Property XXX must be a str or unicode instance, not a tuple

val = "test",

aa = Img( p1 = val )
aa.put()

不要なカンマがある場合などでもこのエラーとなる
BadValueError: Property p1 must be a str or unicode instance, not a tuple

2008年9月3日水曜日

トランザクション エラー Nested transactions are not supported.

1. get_or_insert  自体がトランザクションなのでこれを含めたトランザクションを
  作成しようとするとエラーとなる。

File "C:\Program Files\Google\google_appengine\google\appengine\api\datastore.py",
   line 1386, in RunInTransaction'Nested transactions are not supported.')
BadRequestError: Nested transactions are not supported.


2.動作確認


First up is batch writes. You can now include entities in different entity groups in a single db.put() or db.delete() call. Entity modifications are only atomic within each entity group, but a single call that spans entity groups will be more efficient than a call for each group, which was required before.


以下は SDK だと Cannot operate on different entity groups in a transaction:
となるが Cloud では動作した。

class Dummy2(db.Model):
d1 = db.StringProperty()

class Dummy(db.Model):
d1 = db.StringProperty()

def tran():
d2 = Dummy2(d1 = "aaab")
d1 = Dummy(d1 = "aaab")

d1.put()
d2.put()

tran()


3. その他

   トランザクションの中で検索は実行できない。
  Can't query inside a transaction

2008年9月1日月曜日

YouTube API

http://code.google.com/apis/youtube/articles/youtube_api_appengine.html
に従い進めた。

Developer Key の取得の際は自分でどのように利用するか簡単に記述。
(どこかから値を持ってきて登録するのではない)

けれども、検索するだけであれば
self.developer_key = 'ADD YOUR DEVELOPER KEY HERE'
この部分は不要だった。

チュートリアルのSourceは以下にあるが、これらを特にダウンロードするまでの必要はなかった。
http://code.google.com/p/hello-youtube/source/browse/#svn/trunk/03_hello_youtube_search_query
http://code.google.com/p/hello-youtube/source/browse/#svn/trunk/04_hello_user_input

gdata 関連の設定は既に spredsheet などにアクセスするために導入してあったので
素直に検索を行なうことができた。

Youtube は検索言語の設定により、検索結果がかなり異なるので
http://code.google.com/apis/youtube/reference.html#Query_parameter_definitions
を参考に lr は追加しておいた。

query.vq = search_term
query.max_results = '5'
query.lr = 'ja'

* ja 以外の設定にして "japanese" で検索するとひどい結果になるとの指摘を最近みかけたので。

また、以下の値は検索キーによっては値が得られないことがあるため分岐が必要となる。
rating.average 
 if entry.rating:

2008年8月31日日曜日

NormalizeAndTypeCheck エラー

reference などの key は .key() が必要

○ login.session.key()
× login.session

忘れた場合のエラー

keys, multiple = datastore.NormalizeAndTypeCheckKeys(keys)
File "C:\Program Files\Google\google_appengine\google\appengine\api\datastore.py", line 117, in NormalizeAndTypeCheckK
ys
keys, multiple = NormalizeAndTypeCheck(keys, (basestring, Entity, Key))
File "C:\Program Files\Google\google_appengine\google\appengine\api\datastore.py", line 96, in NormalizeAndTypeCheck
(types, arg, typename(arg)))
adArgumentError: Expected an instance or sequence of (, , ); received (a Session).

2008年8月26日火曜日

mixi openid

Google App Engine上でmixi OpenIDを使ってユーザ認証をするサンプルコード - yanbe.diff - subtech  
を参考にテストしたところ
local:8080 だと動作するが Cloud (GAE に upload すると)だと以下のエラーとなる。
---
Traceback (most recent call last):
File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 499, in __call__
handler.get(*groups)
File "/base/data/home/apps/blog-editor/1.937/mixi_login.py", line 28, in get
request = consumer.begin('https://mixi.jp')
File "/base/data/home/apps/blog-editor/1.937/openid/consumer/consumer.py", line 354, in begin
'No usable OpenID services found for %s' % (user_url,), None)
DiscoveryFailure: No usable OpenID services found for https://mixi.jp
----

以下、参考

http://d.hatena.ne.jp/mitsugi-bb/20080823/1219592219#c


http://www.socialpreneur.info/ja/blog/784

http://ms76.jp/2008/08/22/mixi_openid_for_wordpress/


http://insilico.jognote.com/blog/2008/08/13/curl-%E3%81%AB-https-%E3%81%A7%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%E3%81%A7%E3%81%8D%E3%82%8B%E3%82%88%E3%81%86%E3%81%AB%E8%A8%BC%E6%98%8E%E6%9B%B8%E3%82%92%E8%BF%BD%E5%8A%A0%E3%81%99%E3%82%8B/

---
おそらくこれが原因
Issue 407 http://code.google.com/p/googleappengine/issues/detail?id=407 :
webapp.RequestHandler.redirect missing location header for long urls

2008年8月12日火曜日

spreadsheet からの GAE への upload

GAE SDK付属のdemo/guestbook.py をベースに spreadsheet.google.com のデータを
GAE Cloud の datastore に upload する script を作成
参考ファイルはこちら guestbook.py
今回程度のレコードサイズのデータの場合、read は 150 レコード、 put (write)は 20~30レコード程度毎の処理としました。

利用方法

  1. まず、spreadsheet のデータを読み込みます。

    • 今回は対象は DOW の株価データで 960 レコード程度です。
    • SDK 環境では一度にすべての spreadsheet のデータを読み込むことができましたが、
      cloud では 100 行程度 ( 200行はエラー ) ごとに複数のシートにデータを分割
    • "read" とし、シートの key と シート番号を指定
    •  1 sheet 分のデータを Memcache に読み込みます。


  2. 読み込んだデータを GAE Cloud の datastore に書き込みます。

    • "put" を指定
    • 100 行一度に書き込もうとするとエラーになりますので、今回の場合、20行程度ごとに
      区切り、 offset をかけながら、何度かに分けて書き込み処理を行ないました。


  3. offset は自動的に加算するようにしましたので、[Sign Guest]を繰り返しクリック

  4. 1 sheet 分のデータの upload が完了したら Memcache をクリア
  5. 次のシート番号を指定し、同様の作業を繰り返します。



2008年8月11日月曜日

Memcache API

http://code.google.com/appengine/docs/memcache/

日本語訳 http://d.hatena.ne.jp/technohippy/20080717#1216393318



memcache.add( key, value, time=xx, min_compress_len=0)
time 設定した有効時間(単位秒)以後は再度、検索処理を行なう
Optional expiration time, either relative number of seconds from current time (up to 1 month), or an absolute Unix epoch time. By default, items never expire, though items may be evicted due to memory pressure. Float values will be rounded up to the nearest whole second.   



2008年8月4日月曜日

Debug デバッグ

quick and dirty: きれいではなけれども簡単な方法(開発環境用)
* Cloud ではログにエラー出力されるの危険
import sys
print >>sys.stderr, "xxxxxxx"


正しくは
import logging
logging.debug("xxxxxxx")

def main():
# Set the logging level in the main function
# See the section on Requests and App Caching for information on how
# App Engine reuses your request handlers when you specify a main function
logging
.getLogger().setLevel(logging.DEBUG)
application
= webapp.WSGIApplication([('/', MainPage),
('/sign', Guestbook)],
debug
=True)
webapp
.util.run_wsgi_app(application)

if __name__ = '__main__':
main
()

参考
http://code.google.com/appengine/articles/logging.html
http://code.google.com/appengine/docs/python/logging.html
http://groups.google.com/group/google-appengine/browse_thread/thread/a67752ac402bb21e/345e203a5bdd0750?lnk=gst&q=debug+#345e203a5bdd0750
・Django Middleware で Traceback をコンソールに出力する
http://yamashita.dyndns.org/blog/django-middleware-traceback/

2008年7月23日水曜日

UnicodeEncodeError と webapp.RequestHandler

class MainPage(webapp.RequestHandler):
 の中で
str.decode("utf-8",'ignore')
 とすると
UnicodeEncodeError
 となるようなのですが、
webapp.RequestHandler を介さない別のところで処理している場合、
エラーは発生していない。

UnicodeEncodeError はまだよく理解できていないところがありますが。

メモ

UnicodeEncodeError: 'ascii' codec can't encode characters in position 422-424
: ordinal not in range(128)

Unicode 文字列をバイト列に符号化 (encode) するとき, range(128) つまり 0 から 127 までの文字コードしか扱えない 'ascii' エンコーディングが使われ,日本語文字に対して例外 UnicodeEncodeError が起こったもの
http://www.okisoft.co.jp/esc/cygwin-15a.html

webapp を調べたよ (前編) - Google App Engine
http://d.hatena.ne.jp/hamatsu1974/20080422/1208802967

2008年7月17日木曜日

DeadlineExceededError

DeadlineExceededError のエラー対応を検討

対応例
http://stage.vambenepe.com/archives/category/implementation

結果 google/appengine/runtime/apiproxy.py を参考に

from google.appengine import runtime
from google.appengine.runtime import apiproxy_errors
from google3.apphosting.runtime import _apphosting_runtime___python__apiproxy

これらを import して対応

except runtime.DeadlineExceededError:

File "/base/python_lib/versions/1/google/appengine/runtime/apiproxy.py", line 161, in Wait
rpc_completed = _apphosting_runtime___python__apiproxy.Wait(self)
DeadlineExceededError
だけでなく CancelleError というものもある。
File "/base/python_lib/versions/1/google/appengine/runtime/apiproxy.py", line 189, in CheckSuccess
raise self.exception
CancelledError: The API call datastore_v3.Count() was explicitly cancelled.

2008年7月8日火曜日

Key Limitations: 500 bytes

key_name を設定すると、その分 key が長くなる。
parent を設定すると、親の key が自分の key の先頭に付く。
parent が parent を持っていると、孫の key は長くなる。
限界が 500 byte

従って、当然、 親を設定し、さらにこれに親が設定されていれば
ancestor is  により祖先を検索条件に指定することができる。
b = db.GqlQuery("select * from Blog where ancestor is :1 ", granpa.key())


Tools for storing data: Keys

* Key corresponds to the Bigtable row for an Entity
* Bigtable accessible as a distributed hashtable
* Get() by Key: Very fast! No scanning, just copying data


* Limitations:
o Only one ID or key_name per Entity
o Cannot change ID or key_name later
o 500 bytes

2008年7月7日月曜日

Building Scalable Web Applications/Building a Blog


from google.appengine.ext import db

class BlogIndex(db.Model):
max_index = db.IntegerProperty(required=True,default=0)

class BlogEntry(db.Model):
index = db.IntegerProperty(required=True)
title = db.StringProperty(required=True)
body = db.TextProperty(required=True)


def post_entry(blogname, title, body):
def txn():
blog_index = BlogIndex.get_by_key_name(blogname)
if blog_index is None:
blog_index = BlogIndex(key_name=blogname)
new_index = blog_index.max_index
blog_index.max_index += 1
blog_index.put()
new_entry = BlogEntry(key_name=blogname + str(new_index),parent=blog_index, index=new_index,title=title, body=body)
new_entry.put()
db.run_in_transaction(txn)

def get_entry(blogname, index):
entry = BlogEntry.get_by_key_name(blogname + str(index),parent=Key.from_path('BlogIndex',blogname))
return entry


def get_entries(start_index):
extra = None
if start_index is None:
entries = BlogEntry.gql(
'ORDER BY index DESC').fetch(POSTS_PER_PAGE + 1)
else:
start_index = int(start_index)
entries = BlogEntry.gql(
'WHERE index <= :1 ORDER BY index DESC', start_index).fetch(POSTS_PER_PAGE + 1) if len(entries) > POSTS_PER_PAGE:
extra = entries[-1]
entries = entries[:POSTS_PER_PAGE]
return entries, extra


Building Scalable Web Applications から

Disk Seek を意識している。
Oracle などで Create sequence するように Counter 専用のModel を作成して、
increment("xxxx")するようにしたほうがよいのか。


Writes are expensive!
  • Datastore is transactional: writes require disk access
    • Disk access means disk seeks


  • Rule of thumb: 10ms for a disk seek
  • Simple math:
    • 1s / 10ms = 100 seeks/sec maximum


  • Depends on:
    • The size and shape of your data
    • Doing work in batches (batch puts and gets)

Reads are cheap!
  • Reads do not need to be transactional, just consistent


  • Data is read from disk once, then it's easily cached
  • All subsequent reads come straight from memory


  • Rule of thumb: 250usec for 1MB of data from memory
  • Simple math:
    • 1s / 250usec = 4GB/sec maximum
    • For a 1MB entity, that's 4000 fetches/sec


Tools for storing data: Entities
  • Fundamental storage type in App Engine
  • Set of property name/value pairs
  • Most properties indexed and efficient to query
  • Other large properties not indexed (Blobs, Text)


  • Think of it as an object store, not relational
    • Kinds are like classes
    • Entities are like object instances
  • Relationship between Entities using Keys
    • Reference properties
    • One to many, many to many





Tools for storing data: Entity groups 2

Hierarchical

  • Each Entity may have a parent
  • A "root" node defines an Entity group
  • Hierarchy of child Entities can go many levels deep
    • Watch out! Serialized writes for all children of the root


Datastore scales wide

  • Each Entity group has serialized writes
  • No limit to the number of Entity groups to use in parallel
  • Think of it as many independent hierarchies of data







class CounterConfig(db.Model):
 name = db.StringProperty(required=True)
 num_shards = db.IntegerProperty(required=True,default=1)

class Counter(db.Model):
 name = db.StringProperty(required=True)
 count = db.IntegerProperty(required=True,default=0)

def get_count(name):
 total = 0
 for counter in Counter.gql('WHERE name = :1', name):
  total += counter.count
 return total

def increment(name):
 config = CounterConfig.get_or_insert(name,name=name)
 def txn():
  index = random.randint(0, config.num_shards - 1)
  shard_name = name + str(index)
  counter = Counter.get_by_key_name(shard_name)
  if counter is None:
   counter = Counter(key_name=shard_name, name=name)
  counter.count += 1
  counter.put()
 db.run_in_transaction(txn)

increment("test")
print get_count("test")


def get_count(name):
 total = memcache.get(name)
 if total is None:
 total = 0
 for counter in Counter.gql('WHERE name = :1', name):
  total += counter.count
  memcache.add(name, str(total), 60)
 return total

def increment(name):
 config = CounterConfig.get_or_insert(name,name=name)
 def txn():
  index = random.randint(0, config.num_shards - 1)
  shard_name = name + str(index)
  counter = Counter.get_by_key_name(shard_name)
  if counter is None:
   counter = Counter(key_name=shard_name,name=name)
  counter.count += 1
  counter.put()
 db.run_in_transaction(txn)
 memcache.incr(name)















http://sites.google.com/site/io/building-scalable-web-applications-with-google-app-engine

2008年7月2日水曜日

The parent of an entity is defined when the entity is created, and cannot be changed later.

The parent of an entity is defined when the entity is created, and cannot be changed later.
後から親は替えられない。
http://code.google.com/appengine/docs/datastore/keysandentitygroups.html

Entity Groups, Ancestors and Paths

Every entity belongs to an entity group, a set of one or more entities that can be manipulated in a single transaction. Entity group relationships tell App Engine to store several entities in the same part of the distributed network. A transaction sets up datastore operations for an entity group, and all of the operations are applied as a group, or not at all if the transaction fails.

When the application creates an entity, it can assign another entity as the parent of the new entity. Assigning a parent to a new entity puts the new entity in the same entity group as the parent entity.

An entity without a parent is a root entity. An entity that is a parent for another entity can also have a parent. A chain of parent entities from an entity up to the root is the path for the entity, and members of the path are the entity's ancestors. The parent of an entity is defined when the entity is created, and cannot be changed later.

Every entity with a given root entity as an ancestor is in the same entity group. All entities in a group are stored in the same datastore node. A single transaction can modify multiple entities in a single group, or add new entities to the group by making the new entity's parent an existing entity in the group.

2008年7月1日火曜日

インデックスが必要です no matching index found. This query needs this index

TemplateSyntaxError: Caught an exception while rendering: no matching index found
This query needs this index:
と指摘されたからといって、すぐに index.yaml を修正してはいけない。

1,000 件以上ある kind の先頭のいくらかのデータを
特に検索条件なしで ordery by をかけて fetch するだけのためにも
index が必要になることがあるが、
この index の作成には非常に時間がかかる。

それと並び替えなしの single-property には index は不要
Creating a composite index failed: ascending single-property indexes are not necessary

2008年6月30日月曜日

Model.get_or_insert(key_name, **kwds)

文字どうり、 get_or_insert する。
存在しなけれ r.put()  してくれる。
key_name は省略できない。 key_name は、先頭が数字は不可。
同時に実行されたら 2レコード作成されてしまうかもしれない。
r = Greeting.get_or_insert("Key001", Title="test",  xxx = xxx, .... )

Model.get_or_insert(key_name, **kwds)

Get or create an entity of the model's kind with the given key name, using a single transaction. The transaction ensures that if two users attempt to get-or-insert the entity with the given name simultaneously, then both users will have a model instance that refers to the entity, regardless of which process created it.

Arguments:

key_name
The name for the key of the entity
**kwds
Keyword arguments to pass to the model class if an instance with the specified key name doesn't exist. The parent argument is required if the desired entity has a parent.

The method returns an instance of the model class that represents the requested entity, whether it existed or was created by the method. As with all datastore operations, this method can raise a TransactionFailedError if the transaction could not be completed.

http://code.google.com/appengine/docs/datastore/modelclass.html#Model_get_or_insert

key_name は長いものはだめだったような気がしていたけれども、間違いだった。
ただ、やはり where 句の検索条件には利用できない。

A key_name is stored as a Unicode string (with str values converted as ASCII text). A key_name must not start with a number.

Tip: Key names and IDs cannot be used like property values in queries. However, you can use a named key, then store the name as a property. You could do something similar with numeric IDs by storing the object to assign the ID, getting the ID value using obj.key().id(), setting the property with the ID, then storing the object again.

http://code.google.com/appengine/docs/datastore/keysandentitygroups.html



親に子を追加

p = db.GqlQuery("select * from Oya_model")[0]
r = Ko_model.get_or_insert("Key001",parent=p,att1=200801,...)

子から親を検索 親が見つかったら、その kind と key を表示

pp = db.GqlQuery("select * from Ko_Model")
for p in pp:
if p.parent():
print p.parent().kind(), p.parent_key()

Model.kind() の意味がようやくわかった。
http://code.google.com/appengine/docs/datastore/modelclass.html#Model_kind

Swift UI チュートリアル Loading watchOS が終わらない?

Loading watchOS が終わらない? ディスク容量の残量が少ないので不要なシュミレーターを削除したとこころ watchOSのものが全部なくなってしまっていた。 WatchOS を削除して再度インストールしても復活せず。 Create a new simulator で ...