get_or_insert的TypeError [英] TypeError with get_or_insert

查看:58
本文介绍了get_or_insert的TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.

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

我想念什么?

推荐答案

该错误是由于将 ekey (它是 ndb.Key )作为arg传递给 get_or_insert()(需要一个字符串):

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)

由于您似乎要使用用户的电子邮件作为唯一的密钥ID,因此应直接将 email 字符串传递给 get_or_insert():

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)

这篇关于get_or_insert的TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆