0

我想使用 key 更新实体,但出了点问题。我的代码在这里:

def post(self):
        username = self.request.get("contentb")
        header, response = client.request('https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name='+username+'&count=5000')
        ids = [str(id) for id in json.loads(response)["ids"]]
        messages = []
        userlist = [user.username for user in User.query().fetch(projection=["username"])]
        if username not in userlist:
            user = User()
            user.username = username
            user.follower_list = ids
            key = user.put()
            messages.append("Ok we added you")
        else:
            followerlist = [user.follower_list[0] for user in User.query().filter(User.username == username).fetch(projection=["follower_list"])]
            if len(set(followerlist)-set(ids)) == 0:
                messages.append("No one has unfollowed you :)")
            else:
                for i in set(followerlist)-set(ids):
                    messages.append(str(i) + " " + "unfollowed you")  

            user = key.get()
            user.follower_list = ids
            user.put()
            messages.append("We updated your followerlist")

但我得到错误:

user = key.get()
UnboundLocalError: local variable 'key' referenced before assignment

请你能告诉我哪里错了吗?

4

2 回答 2

0

如果username是 in userlist,那么这意味着该变量key永远不会被创建。在条件结构之外,也许做类似的事情key = ''

于 2013-09-07T08:32:29.907 回答
0
def post(self):
        username = self.request.get("contentb")
        header, response = client.request('https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name='+username+'&count=5000')
        ids = [str(id) for id in json.loads(response)["ids"]]
        messages = []
        userlist = [user.username for user in User.query().fetch(projection=["username"])]
        if username not in userlist:
            user = User()
            user.username = username
            user.follower_list = ids
            key = user.put()
            messages.append("Ok we added you")

        #now user should be in; lets fetch it (update to your needs)
        user = [user for user in User.query().fetch(projection=["username"]) if user.username == username][0]      
        followerlist = [user.follower_list[0] for user in User.query().filter(User.username == username).fetch(projection=["follower_list"])]
        if len(set(followerlist)-set(ids)) == 0:
            messages.append("No one has unfollowed you :)")
        else:
            for i in set(followerlist)-set(ids):
                messages.append(str(i) + " " + "unfollowed you")  

        user.follower_list = ids
        user.put()
        messages.append("We updated your followerlist")
于 2013-09-07T10:58:02.970 回答