我正在使用Python中的Google App Engine开发API。我在向特定网址发送GET请求时遇到问题。我得到了'NoneType'对象没有属性to_dict
错误。麻烦来自apiClient.py中的out = client.to_dict()
,它通过
app.router.add(webapp2.Route(r'/api/client/<clientid:[0-9]+><:/?>', 'apiClient.Client'))
我不明白为什么ndb.Key(db_defs.Client, int(kwargs['clientid'])).get()
返回无
apiClient.py:
import webapp2
from google.appengine.ext import ndb
import db_defs
import json
class Client(webapp2.RequestHandler):
#returns all or a specified client(s)
def get(self, **kwargs):
if 'application/json' not in self.request.accept:
self.response.status = 406
self.response.status_message = "Not acceptable: json required"
return
if 'clientid' in kwargs:
client = ndb.Key(db_defs.Client, int(kwargs['clientid'])).get()
out = client.to_dict()
self.response.write(json.dumps(out))
else:
q = db_defs.Client.query()
keys = q.fetch(keys_only=True)
results = { 'keys' : [x.id() for x in keys]}
self.response.write(json.dumps(results))
db_defs.py:
from google.appengine.ext import ndb
#http://stackoverflow.com/questions/10077300/one-to-many-example-in-ndb
class Model(ndb.Model):
def to_dict(self):
d = super(Model, self).to_dict()
d['key'] = self.key.id()
return d
class Pet(Model):
name = ndb.StringProperty(required=True)
type = ndb.StringProperty(choices=set(["cat", "dog"]))
breed = ndb.StringProperty(required=False)
weight = ndb.IntegerProperty(required=False)
spayed_or_neutered = ndb.BooleanProperty()
photo = ndb.BlobProperty()
owner = ndb.KeyProperty(kind='Client')
class Client(Model):
lname = ndb.StringProperty(required=True)
fname = ndb.StringProperty(required=False)
phone = ndb.StringProperty(required=False)
email = ndb.StringProperty(required=False)
staddr = ndb.StringProperty(required=False)
pets = ndb.KeyProperty(kind='Pet', repeated=True, required=False)
def to_dict(self):
d = super(Client, self).to_dict()
d['pets'] = [p.id() for m in d['pets']]
return d
编辑:
当我向http://localhost:8080/api/client/发出GET请求时,我会收到客户ID列表:
我已验证的{&#34; keys&#34;:[4679521487814656,4855443348258816,5136918324969472, 5242471441235968,5277655813324800,5559130790035456, 5699868278390784,5805421394657280,6051711999279104, 6368371348078592,6544293208522752,6614661952700416, 6685030696878080]}
与GAE数据存储查看器中的相同。
但是当我向http://localhost:8080/api/client/4679521487814656发出GET请求时 我得到了NoneType错误。
答案 0 :(得分:1)
Reveal.configure()
设置为client
,这不是具有None
方法的对象。
to_dict()
为client
,因为以下表达式返回None
:
None
e.g。该密钥没有client = ndb.Key(db_defs.Client, int(kwargs['clientid'])).get()
个对象。