python - 错误 :AttributeError: 'NoneType' object has no attribute 'user_is_member'

标签 python google-app-engine

class Thread(db.Model):
  members = db.StringListProperty()

  def user_is_member(self, user):
    return str(user) in self.members

thread = Thread.get(db.Key.from_path('Thread', int(id)))
is_member = thread.user_is_member(user)

但错误是:

Traceback (most recent call last):
  File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
    handler.get(*groups)
  File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 62, in check_login
    handler_method(self, *args)
  File "D:\zjm_code\forum_blog_gae\main.py", line 222, in get
    is_member = thread.user_is_member(user)
AttributeError: 'NoneType' object has no attribute 'user_is_member'

为什么?

谢谢

最佳答案

您正在尝试通过键获取实体,但不存在具有该键的实体,因此 .get() 返回 None。在尝试对其采取行动之前,您需要检查是否返回了有效实体,如下所示:

thread = Thread.get(db.Key.from_path('Thread', int(id)))
if thread:
  is_member = thread.user_is_member(user)
else:
  is_member = False

或者,等价地:

thread = Thread.get(db.Key.from_path('Thread', int(id)))
is_member = thread.user_is_member(user) if thread else False

关于python - 错误 :AttributeError: 'NoneType' object has no attribute 'user_is_member' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2787319/

相关文章:

python - 单行Python脚本,用于每2个字符用逗号分隔字符串

python - GAE 任务队列异常

python - 谷歌应用引擎上的 webapp、tipfy 或 django

ios - Azure、AWS、同步服务、数据库和 iOS

python - Pandas :分别对每一列进行排序

python - 像字典一样使用空白类合理吗?为什么有人会这么做?

python - 在Tensorflow上工作::ModuleNotFoundError:没有名为'_pywrap_tensorflow_internal'的模块

python - 属性错误 :__exit__ on python 3. 4

python - ndb 异步 "yield next"消费 get_multi 异步

java - 如何在 JDO 中进行批量 Google DataStore 键查找查询