2017-03-16 59 views
0

這是我的代碼。TypeError with get_or_insert

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', '[email protected]') 

我錯過了什麼?

ekey = ndb.Key("Email", email) 
    entity = Email.get_or_insert(ekey) 

因爲它似乎要使用用戶的電子郵件作爲一個獨特的密鑰ID:

回答

1

該錯誤是由路過ekey(這是一個ndb.Key)作爲對Arg的get_or_insert()(這需要一個字符串)引起的您應該直接將email字符串傳遞給get_or_insert()

entity = Email.get_or_insert(email)