【问题标题】:Define variable in init, set the variable in get method, and use it in post method在init中定义变量,在get方法中设置变量,在post方法中使用
【发布时间】:2017-09-20 02:38:34
【问题描述】:

我在我的 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

【问题讨论】:

    标签: python init


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      正确的方法:

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

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

      【讨论】:

        猜你喜欢
        • 2015-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多