I'm new to Python. I can't understand why a variable is None
at a certain point in my code:
class UsersInRoom(webapp.RequestHandler):
def get(self):
room_id = self.request.get("room_id")
username = self.request.get("username")
UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get()
if UserInRoom_entities:
for user_in_room in UserInRoom_entities:
if user_in_room.username == username:
user_in_room.put() # last_poll auto updates to now whenenever user_in_room is saved
else:
user_in_room = UserInRoom()
user_in_room.username = username
user_in_room.put()
// error here, on line 160
UserInRoom_entities = []
UserInRoom_entities.append(user_in_room)
# name is `user_at_room` intead of `user_in_room` to avoid confusion
usernames = [user_at_room.username for user_at_room in UserInRoom_entities]
self.response.out.write(json.dumps(usernames))
The error is:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 507, in __call__
handler.get(*groups)
File "path\to\chat.py", line 160, in get
AttributeError: 'NoneType' object has no attribute 'append'
How is this possible? I'm setting UserInRoom_entities = []
immediately before that call. Or is something else the None
in question?
UPDATE: This code works:
class UsersInRoom(webapp.RequestHandler):
def get(self):
room_id = self.request.get("room_id")
username = self.request.get("username")
UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get()
if UserInRoom_entities:
for user_in_room in UserInRoom_entities:
if user_in_room.name == username:
user_in_room.put() # last_modified auto updates to now whenenever user_in_room is saved
else:
user_in_room = UserInRoom(room=Key(room_id), name=username)
user_in_room.put()
UserInRoom_entities = []
UserInRoom_entities.append(user_in_room)
# name is `user_at_room` intead of `user_in_room` to avoid confusion
usernames = [user_at_room.name for user_at_room in UserInRoom_entities]
self.response.out.write(json.dumps(usernames))
class ChatRoom(db.Model):
name = db.StringProperty()
last_modified = db.DateTimeProperty(auto_now=True)
message_contents = db.StringListProperty()
message_users = db.StringListProperty()
class UserInRoom(db.Model):
room = db.ReferenceProperty(ChatRoom)
name = db.StringProperty()
last_modified = db.DateTimeProperty(auto_now=True)