ndb get& get_or_insert怎么用? (总是提高例外)

时间:2013-03-02 20:42:05

标签: google-app-engine google-cloud-datastore app-engine-ndb

我编写如下代码

from google.appengine.ext import ndb

__metaclass__ = type


class UserSession(ndb.Model):
    session = ndb.BlobProperty()


class KV:
    @staticmethod
    def get(id):
        r = ndb.Key(UserSession, int(id)).get()
        if r:
            return r.session

    @staticmethod
    def set(id, value):
        return UserSession.get_or_insert(int(id), session=value)

    @staticmethod
    def delete(id):
        ndb.Key(UserSession, int(id)).delete()

我写的地方

id = 1
key = ndb.Key(UserSession, int(id))
UserSession.get_or_insert(key, session=1)

sdk raise

TypeError: name must be a string; received Key('UserSession', 1)

当我打电话给KV.get()

sdk raise

文件“/home/bitcoin/42btc/zapp/_plugin/auth/model/gae/user.py”,第14行,获取

    r = ndb.Key(UserSession,int(id)).get()

...

BadRequestError:缺少密钥ID /名称

那么,如何使用NDB?

1 个答案:

答案 0 :(得分:6)

get_or_insert()方法接受一个字符串,该字符串只是键的ID部分,而不是Key。它不能使用数字ID。