这是我的代码。
import webapp2
import json
from google.appengine.ext import ndb
class Email(ndb.Model):
email = ndb.StringProperty()
subscribed = ndb.BooleanProperty()
@staticmethod
def create(email):
ekey = ndb.Key("Email", email)
entity = Email.get_or_insert(ekey)
if entity.email: ###
# This email already exists
return None
entity.email = email
entity.subscribed = True
entity.put()
return entity
class Subscribe(webapp2.RequestHandler):
def post(self):
add = Email.create(self.request.get('email'))
success = add is not None
self.response.headers['Content-Type'] = 'application/json'
obj = {
'success': success
}
self.response.out.write(json.dumps(obj))
app = webapp2.WSGIApplication([
webapp2.Route(r'/newsletter/new', Subscribe),
], debug=True)
这是我的错误。
File "/Users/nick/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 3524, in _get_or_insert_async
raise TypeError('name must be a string; received %r' % name) TypeError: name must be a string; received Key('Email', 'test@test.com')
我错过了什么?
答案 0 :(得分:1)
错误是将ekey
(ndb.Key
)作为arg传递给get_or_insert()
(需要字符串)引起的:
ekey = ndb.Key("Email", email)
entity = Email.get_or_insert(ekey)
由于您希望将用户的电子邮件用作唯一的密钥ID,因此您应该将email
字符串直接传递给get_or_insert()
:
entity = Email.get_or_insert(email)