Search code examples
pythonflasktornado

How to handle both GET and POST requests in TornadoWeb framework?


I'm really new to Python community, it's been a while that I'm trying to learn Flask and Tornado frameworks.

As you know we can handle GET and POST requests together in Flask very easily, For example a simple URL routing in Flask is something like this:

@app.route('/index', methods=['GET', 'POST'])
def index():
    pass

I googled and read Tornado documentation but I couldn't find a way to handle both GET and POST requests together in Tornado.

All I found is like code below:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('intro.html')

    def post(self):
        self.render('intro.html')

Any idea how to do it in Tornado?


Solution

  • You can go with using prepare() method:

    Called at the beginning of a request before get/post/etc. Override this method to perform common initialization regardless of the request method.

    class MainHandler(tornado.web.RequestHandler):
        def prepare(self):
            self.render('intro.html')
    

    Hope that helps.