在init中定义变量,在get方法中设置变量,在post方法中使用
Define variable in init, set the variable in get method, and use it in post method
我在 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
这些方法不是在同一个执行线程中调用的。您的实例数据是线程本地的。如果您希望数据从一个远程调用持续到下一个,您将需要在服务器端存储会话数据,使用某种类型的 cookie 来识别从一个调用到下一个调用的客户端会话。
无论何时使用方法 get
或 set
,始终坚持其含义。从不 set/update get 方法中的任何变量,从不 return set 方法中的任何值。我见过很多人这样做。
正确的方法:
GET method - should always return what you want
SET method - should always set the values and never return anything
话虽如此,您需要在转到 post()
方法之前调用方法 self.get()
。这有助于更新值。
我在 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
这些方法不是在同一个执行线程中调用的。您的实例数据是线程本地的。如果您希望数据从一个远程调用持续到下一个,您将需要在服务器端存储会话数据,使用某种类型的 cookie 来识别从一个调用到下一个调用的客户端会话。
无论何时使用方法 get
或 set
,始终坚持其含义。从不 set/update get 方法中的任何变量,从不 return set 方法中的任何值。我见过很多人这样做。
正确的方法:
GET method - should always return what you want
SET method - should always set the values and never return anything
话虽如此,您需要在转到 post()
方法之前调用方法 self.get()
。这有助于更新值。