错误:赋值前引用的局部变量'key'

时间:2013-09-07 08:27:55

标签: python google-app-engine

我想用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

请告诉我哪里错了?

2 个答案:

答案 0 :(得分:0)

如果username位于userlist,那么这意味着永远不会创建变量key。在条件结构之外,可能会执行key = ''

之类的操作

答案 1 :(得分: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")