[英]'AttributeError: 'NoneType' object has no attribute 'to_dict'
我正在使用Python中的Google App Engine开发API。 我无法将GET请求发送到特定的网址。 我得到的'NoneType'对象没有属性to_dict
错误。 问题out = client.to_dict()
在out = client.to_dict()
中的out = client.to_dict()
上,该路由通过以下方式在main.py中路由到
app.router.add(webapp2.Route(r'/api/client/<clientid:[0-9]+><:/?>', 'apiClient.Client'))
我不明白为什么ndb.Key(db_defs.Client, int(kwargs['clientid'])).get()
返回None
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列表:
{“ keys”:[4679521487814656、4858553348258816、5136918324969472、5242421441235968、5277655813324800、5559130790035456、5699868278390784、5805452394657280、6051711999279104、6368371348078592、6542293208522752、6614661952700416、66650306968780
我已验证的内容与GAE数据存储查看器中显示的内容相同。
但是当我对http:// localhost:8080 / api / client / 4679521487814656进行GET请求时,出现了NoneType错误。
client
设置为None
,这不是使用to_dict()
方法的对象。
client
为None
因为以下表达式返回None
:
client = ndb.Key(db_defs.Client, int(kwargs['clientid'])).get()
例如,没有带有该键的Client
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.