简体   繁体   中英

How to add an instance attribute to a subclass of webapp2.RequestHandler?

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?

要在请求之间传递self.msg之类的数据,您必须使用数据存储区,cookie或webapp2应用程序注册表: http ://webapp-improved.appspot.com/guide/app.html#registry

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM