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

zur*_*roc 1 google-app-engine app-engine-ndb google-cloud-datastore

我写代码如下

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()
Run Code Online (Sandbox Code Playgroud)

我写的地方

id = 1
key = ndb.Key(UserSession, int(id))
UserSession.get_or_insert(key, session=1)
Run Code Online (Sandbox Code Playgroud)

sdk加注

TypeError: name must be a string; received Key('UserSession', 1)
Run Code Online (Sandbox Code Playgroud)

当我打电话给KV.get()

sdk加注

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

    r = ndb.Key(UserSession,int(id)).get()
Run Code Online (Sandbox Code Playgroud)

...

BadRequestError:缺少密钥ID /名称

那么,如何使用NDB?

Gui*_*sum 6

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