TypeError with get_or_insert

2019-09-16 12:05发布

Here is my code.

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)

Here is my error.

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')

What am I missing?

1条回答
Ridiculous、
2楼-- · 2019-09-16 12:21

The error is caused by passing ekey (which is an ndb.Key) as arg to get_or_insert() (which expects a string):

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

Since it appears you want to use the user's email as a unique key ID you should directly pass the email string to get_or_insert():

    entity = Email.get_or_insert(email)
查看更多
登录 后发表回答