Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in python webapp2 how put a __init__ in a handler (for get and post)

Tags:

python

webapp2

How can I create initialization code? When I put the __init__ contructor always tell me that parameters are wrong. Also please gave a example also using __new__ and one using super() and why should we use or not use them.

import webapp2

class MainHandler( webapp2.RequestHandler ):
    def __init__( self ):
        #initialization code/vars
        x = 1

    def get( self ):
        #code for get here
        self.response.write( x+1 )

    def post( self ):
        #code for post here
        self.response.write( x+2 )

app = webapp2.WSGIApplication ( [ ('/', MainHandler) ], debug=True )

like image 586
ZEE Avatar asked Mar 13 '13 23:03

ZEE


2 Answers

Finally got it... The problem is that overriding "webapp2.RequestHandler" requires special special handling

from the webapp2 manual:

If you want to override the webapp2.RequestHandler.init() method, you must call webapp2.RequestHandler.initialize() at the beginning of the method. It’ll set the current request, response and appobjectsasattributesofthehandler. Example:

class MyHandler(webapp2.RequestHandler):
    def __init__(self, request, response):
    # Set self.request, self.response and self.app.
    self.initialize(request, response)
    # ... add your custom initializations here ...
    # ...

...and that's it... now works as expected ;-)

like image 76
ZEE Avatar answered Nov 14 '22 20:11

ZEE


If you aren't passing any arguments or including any of your own code in the __init__ method, there's usually no need to even create one. You'll just use webapp2.RequestHandler's __init__ method.

If you do need to make one, you still have to call webapp2.RequestHandler.__init__:

class theHandler(webapp2.RequestHandler):
    def __init__(self, your_arg, *args, **kwargs):
        super(theHandler, self).__init__(*args, **kwargs)

        self.your_arg = your_arg
like image 3
Blender Avatar answered Nov 14 '22 19:11

Blender