I have the following class definition:

class TestHandler(webapp2.RequestHandler):
    def get(self):
        self.msg = "hello world"
        self.render_form()     # modifies self.msg

    def post(self):
        print self.msg
        #...
        #...
        #...
        self.render_form()

When running, I get the following error:

File "/Users/mhalsharif/Desktop/wordsnet1/ascii-chan/main.py", line 129, in post print self.msg AttributeError: 'AnswersHandler' object has no attribute 'msg'

I am simply trying to save a string in the 'msg' attribute and print it when post() is called. Why cannot I do that? and how to fix it?

有帮助吗?

解决方案

webapp2 will instantiate a new handler per each request it received, so there is no guarantee that if you set self.something in a request you will be able to retrieve the same value with another request, just because self will be a different object.

This is what happens in your case: the handlers that process your get and post requests are not the same instance, so post will not be able to read self.msg simply because it was never set first.

You can review the docs to have a better understanding on what is the lifecycle of a handler.

其他提示

To pass data like your self.msg between request you have to use the datastore, cookies or the webapp2 app registry : http://webapp-improved.appspot.com/guide/app.html#registry

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top