在init中定义变量,在get方法中设置变量,并在post方法中使用它

时间:2017-09-20 02:38:34

标签: python init

我在init方法中将变量设置为空列表。然后,在我的get方法中,我查询数据库并设置列表。接下来,在我的post方法中,我试图使用变量。但是,出于某种原因,当我的post方法运行时,变量会被设置回一个空列表(这可能完全是预期的?)。你能帮我弄清楚我做错了什么,或者让我知道是否还有另外一种方法可以做到这一点?

谢谢!

class thisHandler(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(thisHandler, self).__init__(*args, **kwargs)
        self.topList= []

    def get(self, id):
        if self.user:
            #Other stuff happens
            self.topList = get_myList(id) #This is definitely returning a populated list as it displays just fine on my page
            #Other stuff happens
            self.render('page.html', variables)

    def post(self, id):
        #Other stuff happens
        system.debug(self.topList) #this comes back empty. this is the first reference to it in the post method
        #Other stuff happens

2 个答案:

答案 0 :(得分:0)

不会在同一执行线程中调用这些方法。您的实例数据是线程本地的。如果您希望数据从一个远程调用持久存储到下一个远程调用,则需要在服务器端存储会话数据,使用某种类型的cookie来识别从一次调用到下一次调用的客户端会话。

答案 1 :(得分:0)

每当您使用方法getset时,始终坚持其含义。永远不要在get方法中设置/更新任何变量,也不要从set方法返回任何值。我见过很多人这样做。

正确的方式:

GET method - should always return what you want
SET method - should always set the values and never return anything

话虽如此,您需要在转到self.get()方法之前调用方法post()。这有助于更新价值。